DEV Community

nghihua
nghihua

Posted on

Script tags blocking behavior

1. Script without async or defer (Blocking Script)

  • What it does: This is the default behavior. When the browser encounters this type of script, it will pause parsing of the HTML document until the script is downloaded and executed.
  • What it blocks: It blocks both the HTML parsing and other scripts (if they come after it) from executing until it has completed.
  • Effect on events: These block both the DOMContentLoaded and load events because the browser stops parsing the HTML to download and execute the script, and only resumes once the script is fully executed. This can delay both events, as the browser needs to finish the script execution before continuing.

2. Defer Script

  • What it does: A script with the defer attribute also downloads asynchronously, like async, but the key difference is that it waits until the DOM is fully parsed before executing. It will run after the HTML is parsed, and in the order it appears in the document (even if there are multiple defer scripts).
  • What it blocks: It does not block HTML parsing or the download of other scripts, but it will block execution of subsequent scripts that are placed after it (unless they are also defer).
  • Effect on events: These scripts do not block the DOMContentLoaded event, but they do block the load event. Scripts with defer are executed after the document has been parsed, but before the load event fires (i.e., after DOMContentLoaded).

3. Async Script

  • What it does: A script with the async attribute downloads asynchronously, meaning it doesn't block HTML parsing. However, once it finishes downloading, it will immediately execute (before the HTML parsing is complete and before other scripts).
  • What it blocks: It does not block HTML parsing, but it can interrupt the order of script execution. It will block other scripts if it finishes downloading and executing before them, meaning an async script may run before other scripts (even if they are placed above it in the document).
  • Effect on events: These scripts do not block either the DOMContentLoaded or load events. They are executed as soon as they are downloaded, regardless of the HTML parsing, meaning they do not block the DOM content loading or the overall page load.

Note, however, that scripts will wait on CSS to be downloaded before it can be executed because the JavaScript might query the CSSOM. Thus, even if we inline our JS (without async or defer attribute), DOMContentLoaded will not be fired until after the CSSOM has been constructed.

More on this:
https://web.dev/articles/critical-rendering-path/analyzing-crp

Top comments (0)