DEV Community

Cover image for TIL: Put script tags in head and use the defer attribute
Audrey Roy Greenfeld for Feldroy

Posted on • Updated on

TIL: Put script tags in head and use the defer attribute

I noticed the starter webpage project on Glitch had this in the <head> section:

<!-- import the webpage's javascript file -->
<script src="/script.js" defer></script>
Enter fullscreen mode Exit fullscreen mode

I was surprised to see a <script> tag in the <head> section, since I thought the best practice was to put these before </body>. That couldn't be right...the Glitch devs seem to care about things like this. Then I saw the defer attribute.

MDN says about defer:

This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.

Flavio Copes has a nice writeup on defer and async. My key takeaways:

  • defer only works in the head section.
  • With defer the browser fetches the script in parallel with parsing the HTML. Even if the browser finishes fetching the script, it doesn't run it until it's done HTML parsing.
  • Use defer not async because parsing ideally should complete before script execution.
  • The best practice is what Glitch does, shown above. Put <script src="..." defer> in <head>.

Do you agree with this best practice?

Top comments (0)