简体   繁体   English

我可以用吗<script async> to load babel-polyfill?

[英]Can I use <script async> to load babel-polyfill?

I have a modal dialog on my page that pops up when the user certain kinds of interation with the page. 我的页面上有一个模态对话框,当用户与页面进行某些类型的交互时会弹出该对话框。

I made it with React and used webpack to create a neat little bundle to include in my page via script tag. 我使用React并使用webpack创建了一个整洁的小包,通过脚本标记包含在我的页面中。

Because it uses Generators and I have to support Internet Explorer 11, I need the babel-polyfill , so my HTML code looks like this: 因为它使用Generators并且我必须支持Internet Explorer 11,所以我需要babel-polyfill ,因此我的HTML代码如下所示:

<script src="//cdnjs.cloudflare.com/ajax/libs/babel-polyfill/6.9.1/polyfill.min.js"></script>
<script src="/survey-modal.js" async></script>

What bothers me is that I'm loading the Babel polyfill synchronously. 困扰我的是我正在同步加载Babel polyfill。 If I add async to the first script tag, my code works, but I'm not sure if this is deterministic, ie if the code only works by chance, because the polyfill finished loading before the survey-modal script. 如果我将async添加到第一个脚本标记,我的代码可以工作,但我不确定这是否是确定性的,即代码是否只是偶然的,因为polyfill在调查模式脚本之前完成加载。

Is it safe to use <script async> when loading the babel-polyfill from a CDN? 从CDN加载babel-polyfill时使用<script async>是否安全?

Is it safe to use when loading the babel-polyfill from a CDN? 从CDN加载babel-polyfill时使用是否安全?

No it is not. 不它不是。 async scripts execute "as soon as they are available" and order of execution is not guaranteed. async脚本“一旦可用就执行”,并且不保证执行顺序。 So in the following example: 所以在下面的例子中:

<script src="polyfill.min.js" async></script>
<script src="survey-modal.js" async></script>

there is a possibility that the "polyfill" script executes after "survey-modal". “polyfill”脚本有可能在“survey-modal”之后执行。 A better approach is as follows: 更好的方法如下:

<script src="polyfill.min.js" defer></script>
<script src="survey-modal.js" defer></script>

defer scripts are downloaded after document has been parsed (so it does not block page rendering) but the order of execution is guaranteed. 在解析文档后下载defer脚本(因此它不会阻止页面呈现)但保证执行顺序。

PS: you mentioned that your code works when both scripts are async. PS:您提到当两个脚本都是异步时,您的代码都能正常工作。 Yes, this is by chance. 是的,这是偶然的。 It will work when polyfill is loaded from browser cache and may not work if it is fetched across network. 当从浏览器缓存加载polyfill时它将起作用,如果通过网络获取polyfill可能不起作用。

如果你使用async标签,你不能保证它会在你的模态之前加载,所以我不会那样使用它。

No it's not deterministic and won't always work. 不,它不是确定性的,也不会一直有效。

If you want, you can use throttling on chrome and see that when download speed is low, it won't work always. 如果你愿意,你可以在chrome上使用限制,并看到当下载速度很低时,它总是不起作用。

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

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