首页 > 解决方案 > Javascript 内联脚本和延迟脚本的执行顺序

问题描述

我对混合脚本类型的执行顺序有疑问。

这是我的代码:

    <script>
        if(document.documentMode) {

            const firstScriptInDOM = document.getElementsByTagName('script')[0];
            const polyfill = document.createElement('script');
            polyfill.src = "/static/js/polyfills/polyfills.js";
            firstScriptInDOM.parentNode.insertBefore(polyfill, firstScriptInDOM);
        }
    </script>

    <script src="static/js/lib1.js" defer></script>
    <script src="static/js/lib2.js" defer></script>
    <script src="static/js/lib3.js" defer></script>
    <script src="static/js/myOwnScriptFile.js" defer></script>

如果浏览器是 IE,第一个脚本标签的目的是为 IE 加载 polyfills。然后它应该加载其他脚本并执行我的代码。

我的问题是:polyfills 脚本会阻止延迟脚本的执行吗?

非常感谢您的时间!

标签: javascript

解决方案


脚本同步加载,除非指定使用async属性异步加载,该defer属性的作用是仅在加载 DOM 后加载脚本。如果您动态附加脚本,它将异步加载。

在你的情况下,

这应该是执行链:

  • 检查 polyfill 脚本执行
  • 库1
  • 库2
  • 库3
  • 我的脚本文件
  • polyfills(仅在解析器完成执行后下载)

为了确保所有脚本都按照您想要的顺序加载,您可以使用以下内容动态加载所有脚本:

检查浏览器是否为IE:

IF IE 
 load polyfills, and load other scripts in the onload event of the polyfills script.
ELSE 
 load all other scripts

推荐阅读