DEV Community

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

Posted on • Edited on

3 1

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?

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay