Patrick Hund Patrick Hund - 1 month ago 12
React JSX Question

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="//"></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, i.e. 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.