代码之家  ›  专栏  ›  技术社区  ›  Manngo

javascript async&defer:异步运行脚本

  •  1
  • Manngo  · 技术社区  · 7 年前

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

    假设我有两个脚本:

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

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

    有办法弄到 library.js 脚本到 运行 异步?

    注释

    我发现不同的在线资源在 异步的 属性。

    mdn&whatwg建议,这意味着脚本应该 执行 异步的。其他在线资源建议 负载 异步,但在执行时仍会阻止渲染。

    2 回复  |  直到 7 年前
        1
  •  2
  •   Mamun    7 年前

    我发现 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();
    })();
        2
  •  0
  •   Flimm D. Ben Knoble    7 年前

    两个 defer async 在执行脚本时生效,而不是在下载脚本时生效。我认为混淆源于这样一个事实:有些文档对术语有点草率,而术语 加载 不清楚它是指资源的获取,还是指资源的执行。

    得到 library.js 要在不等待加载文档的情况下异步运行,请使用 异步的 属性,并获取 process.js 要等到分析完文档,请使用 推迟 :

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

    请注意 库.js 以前不能保证运行 进程.js ,尽管可能会。