This is one of the popular frontend interview questions. It tests interviewees knowledge on HTML, JS and Performance.
This is question #1 of Frontend Interview Questions series. If you're looking to level up your preparation or stay updated in general, consider signing up on FrontendCamp.
The script tag is used to add JavaScript to an HTML page. It could be an inline script or an external script.
<body> <!-- Some code before it --> <script> console.log("This is an inline script."); </script> <script src="https://example.com/external-script.js" /> <!-- Some code after it --> </body>
While parsing the HTML, if browser encounters a script tag it will stop HTML parsing and start executing the JS script. If it's inline it will start with execution straight away but if it's an external script, it will be downloaded and then executed.
During this time, when JS script is being downloaded and executed, HTML parsing is blocked. It can only resume once the browser is done with executing the JS script.
Do you see what's wrong here? This will cause performance issues for the end user. If we have a lot of scripts or any script takes a lot of time to execute, user won't see the content of the page for a long time.
To solve exactly this, we have two attributes: async and defer.
If the async attribute is present, the script will be downloaded in parallel to parsing HTML and executed as soon as it is available.
If multiple scripts use the async attribute, the order of execution might be different than the order in which they appear in the HTML. The script that is available first will be executed first.
<body> <!-- Some code before it --> <script async src="https://example.com/external-script.js" /> <!-- Some code after it --> </body>
If the defer attribute is present, the script will be downloaded in parallel to HTML parsing(just like async) but executed after HTML parsing is finished and before firing DOMContentLoaded.
If multiple scripts use the defer attribute, the order of execution will be maintained, unlike async.
<body> <!-- Some code before it --> <script defer src="https://example.com/external-script.js" /> <!-- Some code after it --> </body>
MDN: The script element
FrontendCamp
The above is the detailed content of Understanding async and defer. For more information, please follow other related articles on the PHP Chinese website!