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

<head>
  <script src="app.js"></script>
</head>
Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org 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 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>
Posted by Henning Koch to makandra dev (2021-08-31 13:14)