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.
Scripts with the defer attribute will execute in the order in which they appear in the document. This attribute allows the elimination of parser-blocking JavaScript where the browser would have to load and evaluate scripts before continuing to parse.
Async - means execute code when it is downloaded and do not block DOM construction during downloading process. Defer - means execute code after it's downloaded and browser finished DOM construction and rendering process.
You should use defer for all other scripts. defer is great because it: Gets loaded as soon as possible — so it reduces load times. Doesn't execute until everything you need is ready — so all the DOM you need is there.
JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked. JavaScript in body: A JavaScript function is placed inside the body section of an HTML page and the function is invoked when a button is clicked.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With