4

If an external script defines functions referred to in the HTML (e.g. onclick=...), the script should be located in the <head> so that it will be downloaded immediately to make the functions available to the HTML:

<script src="/.JS/onclicks.js" />

If an external script makes changes to the HTML (e.g. modifies everything with class="special"), it should either be located after the <body>, or located in the <head> with execution deferred until all the HTML has loaded:

<script src="/.JS/highlight-special.js" defer="defer" />

Using defer has the advantage of allowing the script to be downloaded in parallel with the HTML, making the page load more quickly.

There is also the option of providing a script source in the <head> and specifying the async attribute:

<script src="/.JS/highlight-special.js" async="async" />

Like defer, the script is loaded in parallel with the HTML, but rather than waiting until the HTML has loaded to be executed, as soon as the script has loaded the HTML processing temporarily halts while the script executes.

Under what circumstances would using async be useful?

Specifically, the timing isn't predictable, so there doesn't seem to be any advantage to running the script before the HTML has loaded (something that would finish sooner had defer been specified instead).

1 Answer 1

3

The async attribute is useful for a script that:

  1. Doesn't depend on whether the HTML is fully loaded
  2. Shouldn't block the HTML
  3. Yet should still be executed ASAP

A perfect example of this is an analytics script. If you loaded it without any attributes, it would block the rest of the page's rendering. If you loaded it with defer, it would run unnecessarily late in the page cycle, and you might miss sending a pageview event.

For an analytics script, async is just right. Non-blocking, yet still executes asap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.