When should I use the defer attribute on a <script> element in the <head> vs. using a <script> element at the end of the <body>?

Question

When should I use the defer attribute on a <script> element in the <head> vs. using a <script> element at the end of the <body>?

Answer

Using both methods will allow the <script> to load and execute after the HTML has been parsed and loaded, and both methods retain the order of execution - meaning that <script> elements with or without the defer attribute will execute in the order in which they appear in the HTML document. However, at this point in time, more browsers support the use of the <script> element without the defer attribute than those that fully support the use of the defer attribute.

So, if you need to make sure your site or web application supports all browsers, including older browsers, using <script> at the end of the <body> may be the way to go.

Otherwise, defer should be used on <script> elements in the <head>. Using defer like this is potentially faster than using the <script> at the end of the body, as it loads the <script> asyncronosly but waits to execute the <script> until the HTML is parsed and loaded vs. using <script> at the end of the <body>, which will parse then load the HTML, then load the <script>, then execute the <script>.

Another gotcha when using defer - defer doesn’t play nicely with jQuery’s .ready() function. .ready() will execute as soon as the page is interactive (document.readyState === 'interactive') vs. when the page is complete (document.readyState === 'complete'). To make use of the defer attribute, jQuery would need to change it’s .ready() functionality to execute on document.readyState === 'complete' instead of on document.readyState === 'interactive' and without its current functionality, there would a lot of room for bugs when using the jQuery library, as is the case, jQuery has not been updated to fix this issue with defer. Numerous projects depend on .ready() firing when a page becomes interactive vs when it’s complete, updating jQuery to work with defer could potentally break these projects.

9 Likes

What if I used the keyword “defer” on multiple scripts? Which ones run last and how would I know? Thanks!

1 Like

I thought the parsing stops at the

Codecademy

The scripts will be executed in order

<script src="./script1.js" defer></script>
<script src="./script2.js" defer></script>
<script src="./script3.js" defer></script>

It will simply execute the first script, then the second and finally the third

1 Like