Alexis King
Alexis King

Reputation: 43852

Are there any reasons to not use async script elements?

Despite the continued adoption of the script element's async attribute, there is continued advice to place script at the bottom of the document without the async attribute. If document.write is avoided, are there any possible pitfalls when using async?

For example, if I load a script that I wrap in jQuery's $(document).ready(...), is there any chance that I might experience any negative effects when adding the async attribute? Can I reliably specify async on all such scripts?

Upvotes: 0

Views: 72

Answers (1)

Daniel Imms
Daniel Imms

Reputation: 50189

If your scripts rely on being run in a particular order you cannot use async. This typically means that they rely on each other.

A recent example of this that happened to me was using Google's prettyprint syntax highlighting library. You include the library and then make a call to prettyPrint() to apply the syntax highlighting to relevant blocks.

<script src='http://cdnjs.cloudflare.com/ajax/libs/prettify/r298/prettify.js' type='text/javascript'></script>
<script type='text/javascript'>prettyPrint();</script>

So if all your scripts are wrapped in a $(document).ready then they are most likely perfectly fine to go with async. The question you should be asking though is whether you can combine all your files so you only need to make one request.


The defer attribute is similar to async but waits until the HTML is parsed and then runs the scripts in the same order that they appear in your HTML file. This would work in the above situation provided the call the prettyPrint() was external instead of inline as I don't believe it applies to inline scripts.

Upvotes: 2

Related Questions