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


#1

Question

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

Answer

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.