简体   繁体   English

如何动态加载 javascript 并缓存 html

[英]How to load dynamically javascript and cache it html

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.当我尝试使用 XMLHttpRequest 获取数据时,它是同步的,但它没有在浏览器级别缓存。

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如果您想动态加载脚本并确保在使用之前加载它,您可以通过一些技巧同步加载它: https://stackoverflow.com/a/57915593/12031739

The use of document.write is generally frowned upon. document.write的使用通常是不受欢迎的。

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.该文件应根据文件和浏览器的缓存指令进行缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM