CodePark/ questions / Rendering pipeline & critical path
START PRACTICINGPRACTICE
Frontend question · Browser & web performance › Rendering pipeline & critical path

What does parser-blocking JavaScript mean, and why can a stylesheet delay a script from running?

Parser-blocking JavaScript is a classic <script> without async or defer. When the HTML parser reaches it, parsing stops. The script downloads (if it is an external file) and runs, and only then does parsing continue.

Why does the parser stop? The script may call document.write or change the DOM it has seen so far. So the parser can't safely continue. This means a big script in the <head> delays the whole page.

Why CSS can delay a script: scripts can read computed styles, for example with getComputedStyle or offsetWidth. So if a stylesheet comes before a script, the browser waits. It downloads and parses that CSS first, and only then runs the script. A slow stylesheet therefore delays the script. And because the script blocks the parser, it also delays the rest of the parsing.

Fixes:

  • Use defer or async on scripts.
  • Put scripts at the end of the <body>.
  • Inline critical CSS (put the small amount of CSS needed for the first screen directly in the HTML).
  • Keep render-blocking CSS small.
  • Synchronous scripts stop the HTML parser until they download and run.
  • Scripts may read styles, so they wait for any CSS that comes before them.
  • Slow CSS can block JavaScript, and so it also blocks parsing.
  • defer, async, inline critical CSS and smaller stylesheets all help.