简体   繁体   中英

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.

Because it uses Generators and I have to support Internet Explorer 11, I need the babel-polyfill , so my HTML code looks like this:

<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. 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.

Is it safe to use <script async> when loading the babel-polyfill from a CDN?

Is it safe to use when loading the babel-polyfill from a CDN?

No it is not. async scripts execute "as soon as they are available" and order of execution is not guaranteed. 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". 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.

PS: you mentioned that your code works when both scripts are async. 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.

如果你使用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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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