Read more

You should probably load your JavaScript with <script defer>

Henning Koch
August 31, 2021Software engineer at makandra GmbH

It is generally discouraged to load your JavaScript by a <script src> tag in the <head>:

  <script src="app.js"></script>
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show snapshot

The reason is that a <script src> tag will pause the DOM parser until the script has loaded and executed. This will delay the browser's first contentful paint Show snapshot .

A much better default is to load your scripts with a <script src defer> tag:

  <script src="app.js" defer></script>

A deferred script has many useful properties:

  • It does not block the browser from rendering content.
  • Deferred scripts will run after the HTML was parsed. That means you can query the entire DOM tree with querySelector() and friends. document.readyState is 'interactive'.
  • Deferred scripts will run before the DOMContentLoaded event. That means if your code waits to initialize until DOMContentLoaded (many libraries do), it will still work.
  • If you have multiple deferred scripts, they will run in the order they appear in the HTML, regardless of how long individual scripts take to load.
  • You can put your <script> in the <head>, meaning browsers can start loading the script file very early.
  • The <script> tag is grouped together with your other external resources in the <head>.
Posted by Henning Koch to makandra dev (2021-08-31 13:14)