Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between deferred scripts and scripts placed at the end of the page body?

Tags:

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.

like image 945
rodrigoalvesvieira Avatar asked Nov 01 '12 18:11

rodrigoalvesvieira


People also ask

What is a deferred script?

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.

What is the difference between script script async and script defer?

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.

Should you defer all scripts?

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.

What's the difference between putting script in head and body?

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.


1 Answers

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.

like image 199
El Yobo Avatar answered Oct 31 '22 07:10

El Yobo