Concept of pre –
When the browser loads HTML, the HTML parser runs in the main thread and pauses parsing and rendering of the DOM when it encounters a tag until the script has been parsed and executed. This is also known as “rendering blocking.” For example: when we write a piece of code like this
When the HTML parser encounters</script>
Is parsed and executed</script>
In index.js, DOM parsing will be suspended, and the intuitive feeling is that the page is blank for a long time.
This phenomenon can be seen in the Chrome performance panel.
As you can see from the timeline, the execution of the script pauses Parse HTML and continues after the script is finished. This is what we call rendering blocking.
async
MDN details:
For normal scripts, if the async property is present, the normal script is requested in parallel and parsed and executed as soon as possible. This property eliminates parsing blocking Javascript.
If you add async to a script tag, the contents of the script will be loaded asynchronously and as soon as possible (immediately?) after loading. The execution. For example: we add async property to
Take a look at chrome’s performance panel
Parse HTML will not be triggered if the DOM structure is simple and the content is small, and the DOM parsing is complete after the asynchronous loading of the script is completed. If not, parsing will continue after the asynchronous script is executed.
defer
MDN details:
This Boolean property is set to inform the browser that the script will be executed after the document has been parsed and before the DOMContentLoaded (en-US) event is triggered. Scripts with the defer attribute block the DOMContentLoaded event until the script is loaded and parsed.
If you add the defer attribute to the script tag, the content of the script will be loaded asynchronously and, after loading, if the DOM has not been parsed, it will be suspended until the DOM has been parsed. For example, we added the defer attribute to
Take a look at the Chrome performance panel
You can see</script>
The execution of index.js in the DOM parser will not start until DOM parsing is complete.
Conclusion:
Async property Although parsing does not block the DOM, it is executed quickly after parsing, and the execution still blocks the DOM The defer attribute will wait until the DOM parsing is complete and execute the script without blocking DOM parsing