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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.