javascript - 在我的 polyfill 和其他脚本上设置 defer 会保证它们按顺序加载吗?

标签 javascript asynchronous polyfills

我正在使用 polyfill.io 为老客户填充 Promise 和 fetch。在 their website他们建议使用脚本加载器或回调来确保在运行现代代码之前脚本已完全加载:

We recommend the use of the async and defer attributes on tags that load from the polyfill service, but loading from us in a non-blocking way means you can't know for certain whether your own code will execute before or after the polyfills are done loading.

To make sure the polyfills are present before you try to run your own code, you can attach an onload handler to the https://cdn.polyfill.io script tag, use a more sophisticated script loader or simply use our callback argument to evaluate a global callback when the polyfills are loaded:

然而,在两个脚本上设置 defer 不应该已经保证它们被异步加载但仍然按照它们在文档中出现的顺序(除非浏览器不支持 defer)?

<script src="https://cdn.polyfill.io/v2/polyfill.min.js" defer></script>
<script src="modernscript.js" defer></script>

最佳答案

根据 MDN documentation defer属性只是定义了脚本加载发生时的页面加载时间点。

从你引用的文档中可以看出:

To make sure the polyfills are present before you try to run your own code, you can attach an onload handler to the https://cdn.polyfill.io script tag

因为(正如对此答案的评论所指出的那样)无法清楚地看到 defer 是否存在。脚本将被执行(12)并考虑到可能的浏览器实现差异 - 依赖这种行为可能不是最好的主意。

更好的方法是:

  1. 使用一些脚本加载器(例如 RequireJS)
  2. 添加建议onload处理程序到第一个 <script>标记并创建动态 <script>用于在此处理程序中加载代码的标记
  3. 将您的代码与 Promise polyfill 捆绑在一起(手动或使用像 webpack 这样的 bundler )并作为单个 bundle 加载。

更新:正如@PeterHerdenborg 在 comment 中指出的那样- MDN 文档现在明确指出:

Scripts with the defer attribute will execute in the order in which they appear in the document.

关于javascript - 在我的 polyfill 和其他脚本上设置 defer 会保证它们按顺序加载吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47011676/

相关文章:

javascript - Async.whilst 在 async.series 中

c# - Xamarin Gcm 网络管理器等待 httpclient

javascript - Opera mini css3 变换、渐变、过渡 polyfill?

javascript - Angular2 HTTP : Uncaught SyntaxError: Unexpected token < polyfills

C#5 异步方法完成事件。

javascript - 使用 babel-polyfill 的 ChildNode.remove() polyfill

javascript - javascript 文件中的前导分号是什么意思?

Javascript全局变量类型更改

javascript - Ajax 加载后更新监听器的最佳实践

javascript - 当 Reactjs 组件中的 componentWillUnmount 时如何清除异步函数?