Patrick Hund
Patrick Hund

Reputation: 20236

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, 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?

Upvotes: 2

Views: 1878

Answers (3)

Salman Arshad
Salman Arshad

Reputation: 272166

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.

Upvotes: 5

Sachin
Sachin

Reputation: 3540

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.

Upvotes: 0

Dan Purdy
Dan Purdy

Reputation: 371

You can't guarantee it will load before your modal if you use the async tag so I wouldn't use it that way.

Upvotes: 0

Related Questions