This article mainly introduces the JavaScript execution sequence. If you need it, you can refer to the parsing mechanism of the JavaScript engine to explore the working principle of JavaScript, the following uses a more vivid example to illustrate the execution sequence of JavaScript code on the page. If the JavaScript engine's working mechanism is more profound because it belongs to the underlying behavior, the execution sequence of JavaScript code is more visual, because we can intuitively feel the execution sequence, of course, the execution sequence of JavaScript code is complicated, so it is necessary to analyze it before going into the JavaScript language.
1.1 execute JavaScript code in the order of HTML document streams
First, the reader should be clear that the HTML document parsing process in the browser is like this: the browser parses the Page Structure and information from top to bottom based on the document stream. JavaScript code, as embedded scripts, should also be considered part of the HTML document. Therefore, the execution sequence of JavaScript code During loading is determined based on the sequence in which the script tag script appears. For example, when you browse the following document page, you will see that the code is parsed step by step from top to bottom.
The Code is as follows:
Script
Alert ("top script ");
Script
Script
Alert ("header script ");
Script
Script
Alert ("page script ");
Script
Script
Alert ("bottom script ");
Script
If you use the src attribute of script to import external JavaScript file scripts, it will also be executed according to the order in which the statements appear, and the execution process is part of the document loading. The execution will not be extended because it is an external JavaScript file. For example, move the scripts in the header and main area of the above document to an external JavaScript file, and then import them using the src attribute. Preview the document on the page and you will see the same execution sequence.
The Code is as follows:
Script
Alert ("top script ");
Script