HTML5 introduced the defer
attribute for scripts whose loading can be deferred in a HTML page. defer
may be used for any scripts that don’t need to be loaded before the DOM (a.k.a don’t mess with the DOM before it is ready).
For a long time web developers have been advised to put all scripts that don’t need to be loaded before the DOM not in the page head
but before the end of the body
tag instead.
What is the difference between the use of defer
and the long practiced advise? Does the first substitute the latter?
I appreciate any answer. Thank you.
Advertisement
Answer
Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script.
From the WebKit blog, so the behaviour is not necessarily the same across all browsers. So, performance would be better if the scripts are still at the end, as they will be downloaded later.
Edit 2017: browser support is now much better, so you can probably get away with async/defer scripts in the head. It’s still probably a safer choice to put them at the bottom; new browsers will still download them early even if they’re not in the head.
Edit 2020: These days, unless you’re supporting very old browsers, you should just go ahead and use async/defer in the head.