异步JS加载头 [英] Async JS loading in head
问题描述
我需要将脚本异步加载到页面上。我正在使用createElement方法在头部动态插入脚本标记。发生的是首先加载页面源代码。完成后,头部包含的所有元素将并行加载。一旦这一切都加载,我动态添加的脚本加载。
这在逻辑上是有道理的,但我所寻找的是一种方式,我可以加速加载我的动态脚本。我仍然希望它是异步的(不想做document.write),但如果这个脚本可以与head元素的其他脚本并行加载,我们仍然会喜欢它。任何方式,我可以得到这个工作
谢谢
顶部的几行javascript创建动态脚本标签。
< script>
var script = document.createElement(script);
script.src =yourfile.js;
script.async = true; //异步
document.getElementsByTagName(head)[0] .appendChild(script);
< / script>
如需其他选择,请查看此链接: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
I need to load a script asynchronously onto a page. I am using the createElement method to dynamically insert a script tag in the head. What is happening is First the page source loads. When this finishes, all the elements included in the head loads in parallel. Once this is all loaded, the script which I dynamically add loads.
This logically makes sense, but what I am looking for is a way where I can accelerate the loading of my dynamic script. I still want it to be asynchronous (dont want to do document.write) but still would love if this script could be loaded in parallel with other scripts of the head element. Any way I can get this working
Thanks
Put a few lines of javascript at the top creating the dynamic script tag.
<script>
var script = document.createElement("script");
script.src = "yourfile.js";
script.async = true; //asynchronous
document.getElementsByTagName("head")[0].appendChild(script);
</script>
For other alternatives check out this link: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
这篇关于异步JS加载头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!