0

My problem when I am trying to load script dynamically it is becoming async it causing issue when we are trying to use the function in body of html

when i try the XMLHttpRequest to get the data it is sync but it is not getting cached at browser level.

var jsElm = document.createElement("script"); //getting data async
    jsElm.type = "application/javascript";
    jsElm.src = file;
    document.body.appendChild(jsElm);


var xmlhttp=new XMLHttpRequest();//getting data sync but not cached
xmlhttp.send();

I want to know how to load the script which sync and next time load from cache.

ivarni
  • 17,658
  • 17
  • 76
  • 92
guru123
  • 1
  • 2
  • 1
    you are trying to make persistent something you are retrieving dynamically. i guess you have to use some kind of local storage to store and retrieve the scripts and plan some kind of versioning to check whether the cached script is up to date. each load of the page would look for the stored script instead of the dynamically retrieved one. – Tuckbros Oct 15 '19 at 06:39
  • Tuckbros is right. For you that means to create an PWA (progressive web app). Here you'll get more information about this: https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/offline-for-pwa – suther Oct 15 '19 at 07:27
  • There's no Java involved here so I've removed that tag for you. – Thomas Oct 15 '19 at 07:27
  • If I understand this correctly your main issue was that the script was loaded async and you tried to fix that by using `XMLHttpRequest` and now you don't have caching? I'd recommend looking at [this answer](https://stackoverflow.com/a/16231055/957731) and appending a script tag with an `onload` function instead. – ivarni Oct 15 '19 at 08:01

1 Answers1

0

If you want to dynamically load a script and ensure that it is loaded before you use it, you can load it synchronously with a bit of a hack: https://stackoverflow.com/a/57915593/12031739

The use of document.write is generally frowned upon.

As I mention in the answer to that post, it isn't ideal, but it will get the job done.

<script>
document.write(`<script src="${file}"><\/script>`);
</script>

The file should be cached according to cache directives of the file and browser.

Soc
  • 7,425
  • 4
  • 13
  • 30