1. Method of embedding Javascript in HTML
1. Directly place the Javascript code between the tag pairs <script> and </script>
2. Marked by The src attribute specifies an external js file
3. Place it in the event handler, for example:
Click me
4. As the main body of the URL, this URL uses the special Javascript: protocol, such as: Click me< ;/a>The Javascript written in the 3rd and 4th methods needs to be triggered in order to be executed, so unless it is specially set, it will not be executed when the page is loaded.
2. The order in which Javascript is executed on the page
1. The Javascript code on the page is part of the HTML document, so the order in which Javascript is executed when the page is loaded is the order in which the introduction tag appears. External JS inside the tag or introduced through src are executed in the order in which their statements appear, and the execution process is part of the document loading.
2. The global variables and functions defined by each script can be called by scripts executed later.
3. The call to a variable must have been declared previously, otherwise the obtained variable value will be undefined.
To solve this problem, you can use the principle of HTML parsing to parse one HTML tag and then execute the next one, and split the code to achieve this:
3. How to change the execution order of Javascript on the page
1. Use onload
It should be noted that if there are multiple winodws.onload, only the most effective one will take effect. The solution is:
When the HTML parser encounters a script, it must normally terminate parsing the document and wait for the script to execute. To solve this problem, the HTML4 standard defines defer. Use defer to prompt the browser to continue parsing the HTML document and delay execution of the script. This delay is very useful when a script is loaded from an external file, so that the browser does not have to wait for all external files to be loaded before continuing execution, which can effectively improve performance. IE is currently the only browser that supports the defer attribute, but IE does not implement the defer attribute correctly because deferred scripts are always delayed until the end of the document, rather than only delayed to the next non-delayed script. This means that the execution order of delayed scripts in IE is quite confusing, and any functions and variables that are not required by subsequent non-delayed scripts cannot be defined. The execution time of all defer scripts in IE should be after the HTML document tree is established and before window.onload.
3. Use Ajax.
Because xmlhttpRequest can determine the loading status of external documents, it can change the loading order of the code