HTML parse order / script execution order
the following lines are from the official jQuery website
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="http://code.jquery.com/jquery-1.4.2.min.js"><\/script>'开发者_如何转开发);</script>
I'm not sure about the HTML parse order, or should I say script execution order.
The question is: Will line 2 wait for line 1 to load? I doubt it.
If line 1 is still being loaded (say it's 3000KB, and takes long), and line 2 is executed already. window.jQuery would always be false, and so the second js is always included. If that's true, what is line 1 for anyway?
The scripts are executed in the order they are in the document. The browser waits for the script to load before executing the scripts following it.
If this weren't the case, you couldn't have any two files be dependent of each other. You'd have to put everything in the same file because otherwise the script execution order would be practically random.
Yes it will wait with parsing any html until the script is loaded and parsed. This is one reason why you should load externa scripts at the end of your page so script will not blocking the html rendering.
Lets talk about the more traditional way of handling without using attribute defer
or async
The browsers will:
Download
script
s, blocking other resource from downloadingParse the scripts
Execute the scripts
See Ch1, Loading and Executing from High Performance JavaScript
Here's another good reference 12.3. Execution of JavaScript Programs from JavaScript: The Definitive Guide, 4th Edition
精彩评论