工作之余,验证了javascript代码在页面中的执行顺序,只要包括四个位置的测试:文档的头部和底部,window.onload中和$().ready()中;
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <script type="text/javascript"> var s1 = new Date(); //alert("S1:"+s1.getTime()); $('#cs1').val(s1.getTime()); </script> <script type="text/javascript" src="http://style.org.hc360.com/js/build/source/core/jquery.min.js"></script> <script type="text/javascript"> window.onload=function(){ var s2 = new Date(); //alert("S2:"+s2.getTime()); $('#cs2').val(s2.getTime()); } $().ready(function() { var s3 = new Date(); //alert("S3:"+s3.getTime()); $('#cs3').val(s3.getTime()); }); </script> </head> <body> <input id="cs1" data-log="第一个input"/> <input id="cs2" data-log="第二个input"/> <input id="cs3" data-log="第三个input"/> <input id="cs4" data-log="第四个input"/> <img src="http://img00.hc360.com/b2b/201209/201209221600084438.jpg" data-log="第一个img"div/> <img src="http://img00.hc360.com/b2b/201209/201209221601586910.jpg" data-log="第二个img" /> <img src="http://img00.hc360.com/b2b/201209/201209051709119579.jpg" data-log="第三个ing" /> <img src="http://img00.hc360.com/b2b/201209/201209051712521920.jpg" data-log="第三个ing" /> <img src="http://img00.hc360.com/b2b/201209/201209131458144185.jpg" data-log="第三个ing" /> <img src="http://img00.hc360.com/b2b/201209/201209131500093424.jpg" data-log="第三个ing" /> <img src="http://img00.hc360.com/b2b/201209/201209221605226829.jpg" data-log="第三个ing" /> <img src="http://img00.hc360.com/b2b/201209/201209221607425487.jpg" data-log="第三个ing" /> <img src="http://img616.ph.126.net/g9ocgi2F9ovgJ0LofF28mg==/1704612458961497506.jpg" data-log="第三个ing" /> </body> <script type="text/javascript"> var s4 = new Date(); $('#cs4').val(s4.getTime()); //alert("S4:"+s4.getTime()); </script> </html>
验证结果如下:
因为头部的javascript执行时dom还没有在页面中渲染,所有s1中没有,显示数据,但是是第一个执行的,可以用alert顺序证明。依次执行的顺序是:S1>S4>S3>S2.