Blocking download of external JS
When all browsers download JS, they will block all other activities, such as the download of other resources, the presentation of content, etc. After the JS is downloaded, parsed, and executed, other resources will be downloaded in parallel and the content will be presented.
Some people may ask: Why can’t JS be downloaded in parallel like CSS and image? Here we need to briefly introduce the principle of how browsers construct pages.
When the browser receives the HTML document from the server and converts the HTML into a DOM tree in memory, during the conversion process, if a certain node is found If CSS or IMAGE is referenced, another request will be sent to request CSS or image, and then the following conversion will continue without waiting for the return of the request. When the request returns, only the returned content needs to be put into the DOM tree. The corresponding position in is OK. But when JS is referenced, the browser sends a js request and will wait for the return of the request. Because the browser needs a stable DOM tree structure, and it is very likely that there is code in JS that directly changes the DOM tree structure, such as using document.write or appendChild, or even directly using location.href to jump, the browser wants to Prevent JS from modifying the DOM tree and needing to rebuild the DOM tree, so it will block other downloads and renderings.
Blocked download diagram: The picture below is the time waterfall diagram of accessing the blogjava homepage. You can see the start The two images are downloaded in parallel, and the following two JS are blocked in downloading (one downloaded each).
Blocking download of embedded JS
Embedded JS refers to JS code written directly in the HTML document. As mentioned above, referencing external JS will block subsequent resource downloads and subsequent content rendering. How will the embedded JS be blocked? Look at the following two codes:
Code 1: