What will happen if I put a <script> element in the <head> instead of at the end of the <body>?


What will happen if I put a <script> element in the <head> instead of at the end of the <body>?


Although our HTML will be valid if we use a <script> element in either the <head> or <body> element, we normally want to put our <script> elements before our closing </body> tag instead of in the <head> element. We do this because if one of our <scripts> fails to load, any content on our page physically lower than the failing <script> may not render or will error if we are trying to manipulate an element that doesn’t exist yet in the DOM. We could be left with a blank page with no HTML or styling! Also, if we are waiting for our <script> to download, the rest of the content on our page will have to wait to render until our <script> is loaded. It’s better practice to put our <script> elements before the closing </body> tag to make sure all our our HTML content is read/rendered by the browser before trying to apply JavaScript.


Maybe I’m confused but i thought that in an earlier lesson it was suggested that one should put it in the head and use defer. Is there a preferable method?


Hey @blogwhiz93672! This is a completely valid question, I just made a post that goes over why/when we would use defer on a <script> in the <head> vs. a <script> at the end of the <body> here: 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>?

It’s sort of a long explanation, but the tl;dr (too long didn’t read) is that jQuery hasn’t been updated to make use of the defer attribute, and is why we wouldn’t use defer in the jQuery lessons (and when using jQuery).