You should probably load your JavaScript with <script defer>

Updated . Posted . Visible to the public. Repeats.

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

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

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 archive.org snapshot .

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

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

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>.

Deferring inline scripts

You cannot defer inline <script> tags. However, you can use <script type="module">, which is deferred by default:

<script type="module">
  console.log("I'm running deferred")
</script>
Henning Koch
Last edit
Henning Koch
Keywords
script, at, before, end, of, body
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2021-08-31 11:14)