简体   繁体   English

页面完全加载后执行不重要的 Javascript 文件

[英]Execute unimportant Javascript files after the page fully loads

In my site I have many javascript files, for example:在我的站点中,我有许多 javascript 文件,例如:

<script src="script1.js"></script>
<script src="script2.js"></script> 
<script src="script3.js"></script> 
<script src="script4.js"></script>
<script src="script5.js"></script>

these are slowing my website's load time.这些正在减慢我网站的加载时间。 so my idea is to load these script files 2 sec after the page fully loads, I am already using defer but I want to load these (script files) in more delay in order to load my pages faster.所以我的想法是在页面完全加载后 2 秒加载这些脚本文件,我已经在使用 defer 但我想更延迟地加载这些(脚本文件),以便更快地加载我的页面。

using jQuery we can append new script tags like this after particular interval of time say 3000 ms.使用 jQuery 我们可以 append 像这样的新脚本标签在特定的时间间隔后说 3000 毫秒。

<script type="text/javascript">
 jQuery( document ).ready(function() {
    setTimeout(function(){ 
      var my_awesome_script = document.createElement('script');    
      my_awesome_script.setAttribute('src','http://example.com/site.js');    
      document.head.appendChild(my_awesome_script);
      
    }, 3000);
});
</script>

The best option here is to use internal js, instead of external script files.这里最好的选择是使用内部 js,而不是外部脚本文件。 Because external script files have higher importance and they will be loaded along with the page.因为外部脚本文件具有更高的重要性,它们将与页面一起加载。 So, if you want the JS to start after the HTML, CSS and Images have completely loaded, change the code into internal JS and use one of these methods:因此,如果您希望 JS 在 HTML、CSS 和图像完全加载后启动,请将代码更改为内部 JS 并使用以下方法之一:

window.onload = function ...

This allows you to call a function once the window has been completely loaded.这允许您在 window 完全加载后调用 function。

window.addEventListener("load", function(){
// ....
});

This event listener allows you to call a JS function once the page is completely loaded and parsed.此事件侦听器允许您在页面完全加载和解析后调用 JS function。 Try one of these尝试其中之一

let scriptSources = ['script1.js', 'script2.js', 'script3.js'];

scriptSources.forEach(loadLater)

function loadLater(item, index) {
    
setTimeout(function(){ 

    let script =  document.createElement('script');
    script.src = item;

    document.body.appendChild(script); 
    
    }, 2000 * (index + 1) );
}

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

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