We know that JavaScript is an interpreted language, and its execution is top-down. However, each browser has slightly different understanding of top-down, and the upstream and downstream of the code, that is, the program flow, are crucial to the correctness of the program. important, so I think it is necessary to have a deep understanding of the execution order of multiple js blocks.
First of all, we need to know how many methods there are to add javaScript to the page? The first two types below are common, but there are actually more.
1. Directly introduce external js files into the page:
2. Directly write js fragments into the page
"); " "ipt>Note: At this time, "..
" must be split into "
alert(1)
");
You may think this is not necessary. Since it is already in the script, why add another layer? Haha, it is a way of writing, and it has its own special behavior, which we will discuss later.
5. Use xmlHttpRequest in Ajax combined with eval() to introduce js. I first saw it in Dojo code and wrote it in more detail:
var ajaxRequest = getXmlHttpRequest()//Save the need for each browser to get xmlHttpRequest Department
ajaxRequest.open("GET","my.js",false);//Synchronous call using the Get method of the xmlHttpRequest object
ajaxRequest.send(null);
sJsFragment = ajax.responseText ;//Get the string as a js fragment
eval(sJsFragment);//Execute the js fragment
Note: It is required that the content of my.js and later sJsFragment must be very standardized js, and there must be no beginning with // Comment, how to check whether js is standardized? Go to http://jslint.com/
6. The omnipotent Dom method. I first saw this in Yahoo’s front-end code. It is very powerful and written in detail:
var oScript = document. createElement("script");//Create a Script element
oScript.src = "my.js";//Specify the src attribute
document.getElementsByTagName("head")[0].appendChild(oScript) ;
Note: The content of my.js will be obtained and executed after oScript is added to the document. If you look carefully at this paragraph, you can easily find that this call is asynchronous and can be triggered by an event after the document is loaded. I used it to modify it as a replacement for the Get method of xmlHttpRequest when fetching data across domains, and achieved a perfect result. As a result, I will have the opportunity to write a special article in the future.
There are quite a few of six types, and there may be more. Moreover, these types may be nested within each other and change constantly. The execution order of javaScript introduced in methods 1, 2, 4, and 6 is very natural. As the page is loaded and subsequent events are triggered, they follow a first-come, first-served basis and are internally top-down. <script>alert(1)</script>Our main concern is the problems caused by the third and fourth methods of introducing js (please indicate the source when reposting: http://blog.csdn.net/lenel)