admin管理员组文章数量:1410730
I don't want to call the JavaScript functions at the startup. The reason is simple, it will reduce the initial download size and the page will be appear faster. To do that I used the following code inside head section..
<script type="text/javascript">
// Add a script element as a child of the body
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "deferredfunctions.js";
document.body.appendChild(element);
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
But it did not work...please help me
I don't want to call the JavaScript functions at the startup. The reason is simple, it will reduce the initial download size and the page will be appear faster. To do that I used the following code inside head section..
<script type="text/javascript">
// Add a script element as a child of the body
function downloadJSAtOnload() {
var element = document.createElement("script");
element.src = "deferredfunctions.js";
document.body.appendChild(element);
}
// Check for browser support of event handling capability
if (window.addEventListener)
window.addEventListener("load", downloadJSAtOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", downloadJSAtOnload);
else window.onload = downloadJSAtOnload;
</script>
But it did not work...please help me
Share Improve this question edited Jul 7, 2011 at 13:50 curtisk 20.2k4 gold badges60 silver badges74 bronze badges asked Jul 7, 2011 at 13:47 Sajib ShomeSajib Shome 111 silver badge2 bronze badges 1- Related: stackoverflow./questions/912711/… – masoud Commented Apr 11, 2015 at 11:03
3 Answers
Reset to default 4Usually, it's better to put scripts in the end of your body, and call them immediately.
Scripts block loading of the page, so putting them at the end of body allows the page to load quickly, and the javascript will load with page already ready.
document.head.appendChild(element)
You can use <script defer>
(defer attribute on HTML script tag).
Example:
<script src="link/to/yourfile.js" defer></script>
defer
will download the file during HTML parsing and will only execute it after the parser has pleted. defer scripts are also guaranteed to execute in the order that they appear in the document.
本文标签: How to defer loading of JavaScript fileStack Overflow
版权声明:本文标题:How to defer loading of JavaScript file? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744876321a2629933.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论