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