Web Technology Basics
In the processing a browser does before showing the first screen (the critical rendering path), a <script src="app.js"> written without attributes inside <head> makes the HTML parser stop at that point. Which of the following correctly describes the behavior when the defer attribute is added to this element?
- AIt is executed immediately as soon as the download finishes, stopping the HTML parser, and the execution order of multiple scripts is not guaranteed
- BIt is neither downloaded nor executed, and is loaded only when the user first interacts with the page
- CIt is downloaded while the HTML parser keeps working and executed after the document has been parsed, in the order written in the document
Show answer and explanation
Answer: C. It is downloaded while the HTML parser keeps working and executed after the document has been parsed, in the order written in the document
The browser parses HTML to build the DOM and CSS to build the CSSOM, combines the two to decide what to draw, calculates the positions and sizes of elements (layout) and then draws them (paint). A script element without attributes may rewrite the DOM, so the HTML parser stops until the script has been downloaded and executed. With defer, the download proceeds while the parser keeps working, and execution happens after the whole document has been parsed, in the order written in the document. With async, a script runs as soon as its download finishes, so the order is not guaranteed.
- A. This is the behavior of the async attribute. With defer, scripts run after the document has been parsed, in the order written.
- B. Even with defer, the script is downloaded right away and executed without waiting for user interaction.
- C. Correct. It is downloaded without stopping the parser and executed after the document has been parsed, in the order written.