简体   繁体   English

如何延迟加载 JavaScript 文件?

[英]How to defer loading of JavaScript file?

I don't want to call the JavaScript functions at the startup.我不想在启动时调用 JavaScript 函数。 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..为此,我在 head 部分中使用了以下代码..

<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但它没有用......请帮助我

Usually, 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.脚本会阻止页面的加载,因此将它们放在正文的末尾可以让页面快速加载,并且 javascript 将加载页面已经准备好。

You can use <script defer> (defer attribute on HTML script tag).您可以使用<script defer> (HTML 脚本标签上的 defer 属性)。

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 completed. defer将在 HTML 解析期间下载文件,并且仅在解析器完成后执行。 defer scripts are also guaranteed to execute in the order that they appear in the document. defer 脚本也保证按照它们在文档中出现的顺序执行。

document.head.appendChild(element)

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

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