This article is mainly based on several ways to introduce JavaScript into HTML pages, analyzing the execution order of JavaScript scripts in HTML
1. Regarding the blocking nature of JavaScript script execution
JavaScript has blocking characteristics when it is parsed and executed in the browser. That is to say, when the JavaScript code is executed, the parsing, rendering and downloading of other resources must stop and wait for the script to complete①. This is uncontroversial, and the behavior is consistent in all browsers. The reason is not difficult to understand: the browser needs a stable DOM structure, and JavaScript may modify the DOM (change the DOM structure or modify a certain DOM node), if the parsing of the page continues while JavaScript is being executed, the entire parsing process will become difficult to control, and the possibility of parsing errors will also become very high.
However, there is another issue that needs attention here. For external scripts, it also involves a script download process. In early browsers, the download of JavaScript files would not only block the parsing of the page, but even block other resources on the page. Downloads (including other JavaScript script files, external CSS files, and external resources such as images). Starting from IE8, Firefox3.5, Safari4 and Chrome2, parallel downloading of JavaScript is allowed. At the same time, the downloading of JavaScript files will not block the downloading of other resources (in older versions, the downloading of JavaScript files will also block the downloading of other resources).
Note: Different browsers have different restrictions on the maximum number of connections under the same domain name. The requirement in the HTTP1.1 protocol specification is that it cannot be higher than 2, but most browsers currently provide a maximum number of connections. More than 2, IE6/7 both have 2, IE8 has been upgraded to 6, firefox and chrome also have 6. Of course, this setting can also be modified. For details, please refer to: http://www.stevesouders. com/blog/2008/03/20/roundup-on-parallel-connections/
2. About the execution order of the script
Browsers parse pages in order from top to bottom, so under normal circumstances, the execution order of JavaScript scripts is also from top to bottom, that is, the code that appears first on the page or the code that is introduced first is always executed first. execution, even when parallel downloading of JavaScript files is allowed. Note that we have marked "under normal circumstances" in red here. What is the reason? We know that there are many ways to add JavaScript code to HTML, which are summarized as follows (regardless of module loaders such as requirejs or seajs):
(1) Normal introduction: that is, introducing script code or introducing external scripts through the