测试一:
test.html
<html> <head> <title> javascript记载顺序研究 </title> <script type="text/javascript" src="1.js" ></script> <script type="text/javascript" src="2.js" ></script> <script type="text/javascript" src="3.js"></script> </head> <body> <div> this is just a Test </div> <div id="container1"> </div> </body> </html>
*.js
alert("1") //1.js
alert("2") //2.js
alert("3") //3.js
执行结果:在“this is just a Test出现前,alert()语句依次执行,执行完成后,this is just a Test 出现”
测试2:
test.html
<html> <head> <title> javascript记载顺序研究 </title> </head> <body> <script type="text/javascript" src="1.js" ></script> <div> this is just a Test </div> <div id="container1"> </div> <script type="text/javascript" src="2.js" ></script> <script type="text/javascript" src="3.js"></script> </body> </html>
*.js
alert("1") //1.js
alert("2") //2.js
alert("3") //3.js
执行结果:alert("1")->"this is just a Test 出现"->alert("2")->alert("3")
测试3:
test.html
<html> <head> <title> javascript记载顺序研究 </title> </head> <body> <script type="text/javascript" src="a.js" ></script> <div> this is just a Test </div> <div id="container1"> </div> <script type="text/javascript" src="b.js" ></script> </body> </html>
a.js
alert("aaa");
document.getElementById("container1").innerHTML="aaa";
b.js
alert("bbb");
document.getElementById("container1").innerHTML="bbb";
执行结果:alert("aaa")->“运行document.getElementById("container1").innerHTML="aaa"报错,document.getElementById("container1")为空”->alert("bbb")->"运行document.getElementById("container1").innerHTML="bbb"成功"
由一,二,三测试可以看出,在页面中的<script></script>同样会被作为一般的页面元素,按页面顺序加载。与普通DOM不同的是,<script>中的脚本会在加载过程中解释执行。在执行过程中,不能使用未加载的DOM
测试四:
test.html
<html> <head> <title> javascript记载顺序研究 </title> <script type="text/javascript" src="a.js" ></script> </head> <body> <div> this is just a Test </div> <div id="container1"> </div> <div id="container2"> Test <div> <script type="text/javascript" src="b.js" ></script> </body> </html>
a.js
window.οnlοad=function (){ alert("aaa"); document.getElementById("container1").innerHTML="aaa"; }
b.js
alert("bbb");
document.getElementById("container2").innerHTML="bbb";
执行结果:
alert("bbb");->document.getElementById("container2").innerHTML="bbb";->window.onload()->...
测试四表面:window.onload()函数是在页面元素全部加载后再执行。
测试五:
test.html
<html> <head> <title> javascript记载顺序研究 </title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="a.js" ></script> </head> <body> <div> this is just a Test </div> <div id="container1"> </div> <div id="container2"> Test <div> </body> </html>
a.js
window.οnlοad=function (){ alert("aaa"); document.getElementById("container1").innerHTML="aaa"; } $(function(){ alert("$aaa"); })
测试结果:alert("$aaa")->alert("aa")表明jquery的$(document).ready(function(){})比window.onload先执行。