DEV Community

loading...
Cover image for TIL: Put script tags in head and use the defer attribute
Feldroy

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

Audrey Feldroy
Engineer, artist, and writer. Co-author of Two Scoops of Django and Django Crash Course. Core committer to @danielfeldroy πŸ’˜and Uma 🍼 Formerly a RoyGreenfeld.
・Updated on ・1 min read

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>

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?

Discussion (0)

Forem Open with the Forem app