JavaScript异步和延迟:异步运行脚本

时间:2018-11-13 04:58:10

标签: javascript asynchronous

据我所知,在script元素中,async属性允许脚本异步下载(类似于图像),而defer使脚本等待直到执行结束为​​止。

假设我要包含两个脚本:

<script src="library.js"></script>
<script src="process.js"></script>

我希望它们都异步进行,我希望process.js等到最后开始处理。

是否有一种方法可以使library.js脚本异步运行

注意

我发现,关于async属性的实际作用,不同的在线资源之间似乎存在一些差异。

MDN和WhatWG建议,这意味着脚本应执行异步。其他在线资源建议它应 load 异步加载,但在执行时仍会阻止渲染。

2 个答案:

答案 0 :(得分:2)

我发现Sequential script loading in JavaScript可以为您提供帮助:

(function(){
  
  //three JS files that need to be loaded one after the other
  var libs = [
    'https://code.jquery.com/jquery-3.1.1.min.js',
    'https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js',
    'https://cdnjs.cloudflare.com/ajax/libs/underscore.string/3.3.4/underscore.string.js'
  ];
  
  var injectLibFromStack = function(){
      if(libs.length > 0){
        
        //grab the next item on the stack
        var nextLib = libs.shift();
        var headTag = document.getElementsByTagName('head')[0];
        
        //create a script tag with this library
        var scriptTag = document.createElement('script');
        scriptTag.src = nextLib;
        
        //when successful, inject the next script
        scriptTag.onload = function(e){
          console.log("---> loaded: " + e.target.src);
          injectLibFromStack();
        };    
        
        //append the script tag to the <head></head>
        headTag.appendChild(scriptTag);
        console.log("injecting: " + nextLib);
      }
      else return;
  }
  
  //start script injection
  injectLibFromStack();
})();

答案 1 :(得分:0)

deferasync都会影响何时执行脚本,而不影响何时下载脚本。我认为造成混淆的原因是某些文档的术语有点草率,而术语 loaded 尚不清楚它是指获取资源还是执行资源。< / p>

要使library.js在不等待文档加载的情况下异步运行,请使用async属性,并要使process.js等待文档被解析,请使用{{1} }:

defer

请注意,尽管可以保证<script src="library.js" async></script> <script src="process.js" defer></script> 可以在library.js之前运行。

相关问题