现在前端用javascript用的比较多,当然真心的说这个语言是一个非常业余的语言,但是用的人很多,所以也比较火。今天想完成一个javascript外部文件自动加载的设计(类似于java或者php的import和require_once),因此仔细研究了下Javascript的解析顺序,发现要真正的实现javascript的动态加载是无法完美实现的(所以现在所有的js库都会放在一个js文件里面,然后让你在head部分通过src引入)。其实javascript的解析顺序非常的简单,Javascript解析的基本顺序原则是:从上到下,同步解析。也就是解析完前一段javascript代码,才会继续解析后面的代码。如果通过javascript代码动态加载的代码部分,这属于异步解析的,通常会在整个HTML解析完毕之后才会解析动态加载的部分。(IE10,Chrome29,FireFox34上得到验证)。
示例代码如下:
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 2 "http://www.w3.org/TR/html4/loose.dtd"> 3 <script>window.console.log("html befor...");</script> 4 <html xmlns="http://www.w3.org/1999/xhtml"> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7 <script src='myjs/autoload.js'></script> 8 <title>New Web Project</title> 9 </head> 10 <script>window.console.log("head after...");</script> 11 <script src='myjs/autoload.js'></script> 12 <body> 13 <script src='myjs/HelloDate.js'></script> 14 <script src='myjs/Student.js'></script> 15 <script> 16 LoadScriptEnd("myjs/HelloDate.js", loadend); 17 LoadScriptEnd("myjs/Student.js",loadend2); 18 function loadend() 19 { 20 var obj = new HelloDate(); 21 document.getElementsByTagName("h2")[0].innerHTML = obj.GetDateStr(); 22 23 } 24 25 function loadend2() 26 { 27 var stu=new Student("1001","jackwong","man"); 28 document.getElementsByTagName("h3")[0].innerHTML=stu.DispInfo(); 29 30 } 31 32 33 </script> 34 35 <h1>New Web Project Page</h1> 36 <h2>this is end!</h2> 37 <h3>this is end2!</h3> 38 39 <script>window.console.log("body script end");</script> 40 </body> 41 42 <script>for(var i=0;i<100000000;i++)m++;</script> 43 <script>window.console.log("body after...");</script> 44 </html> 45 <script>window.console.log("html after...");</script>
以上代码里面LoadScriptEnd函数是动态加载外部 js文件的函数,你的你能说出里面的代码执行顺序吗?
正确的执行顺序应该是:
1 "html befor..." Jstest.html:3 2 "autoload begin" autoload.js:1 3 "autoload end" autoload.js:62 4 "head after..." Jstest.html:10 5 "autoload begin" autoload.js:1 6 "autoload end" autoload.js:62 7 "HelloDate begin" HelloDate.js:1 8 "HelloDate end" HelloDate.js:17 9 "Student begin" Student.js:1 10 "Student end" Student.js:13 11 "LoadScriptEnd begin" autoload.js:33 12 "LoadScriptEnd Return" autoload.js:60 13 "LoadScriptEnd begin" autoload.js:33 14 "LoadScriptEnd Return" autoload.js:60 15 "body script end" Jstest.html:40 16 "body after..." Jstest.html:44 17 "html after..." Jstest.html:46 18 "Student begin" Student.js:1 19 "Student end" Student.js:13 20 "LoadScriptEnd OK" autoload.js:55 21 "HelloDate begin" HelloDate.js:1 22 "HelloDate end" HelloDate.js:17 23 "LoadScriptEnd OK" autoload.js:55