jQuery $(document).ready()执行顺序
来源:广州中睿信息技术有限公司官网
发布时间:2012/10/21 23:25:16 编辑:admin 阅读 476
jQuery的官方网站的解释如下:&ldquoWhileJavaScriptprovidestheloadeventforexecutingcodewhenapageisrendered,thise

jQuery的官方网站的解释如下:


While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code.

当页面DOM 元素全部加载完毕后就执行.ready()。


如果在.ready()执行之前有javascript代码存在,那么javascript将怎么执行呢?
答案是先执行.ready()之前的javascript代码,然后执行.ready()。

写个example

<!DOCTYPE html>  <html>  <head></head>  <body>   <span>This page is shown to understand '$(document).ready()' in jQuery. <br /><span>   <p>    If you see this line, it means DOM hierarchy has been loaded. NOW loading jQuery from server and execute JS...<br /><br />   </p>      <script src="http://code.jquery.com/jquery-latest.js"></script>   <script>    document.write('The JS is doing sth after DOM loaded and before executing $(document).ready()...<br /><br />');    //alert('The JS is doing sth after DOM loaded and before executing $(document).ready()...');        document.write('DOM is loaded and $(document).ready() will now be executed!<br /><br />');    //alert('DOM is loaded and $(document).ready() will now be executed!');        $(document).ready(function () {     $(document.body).append("$(document).ready() is now been executed!!!<br /><br />");     //alert("$(document).ready() is now been executed!!!");    });   </script>  </body>  </html>  

执行完页面打印出来的顺序是:

This page is shown to understand '$(document).ready()' in jQuery.     If you see this line, it means DOM hierarchy has been loaded. NOW loading jQuery from server and execute JS...      The JS is doing sth after DOM loaded and before executing $(document).ready()...    DOM is loaded and $(document).ready() will now be executed!    $(document).ready() is now been executed!!!  

  

联系我们CONTACT 扫一扫
愿景:成为最专业的软件研发服务领航者
中睿信息技术有限公司 广州•深圳 Tel:020-38931912 务实 Pragmatic
广州:广州市天河区翰景路1号金星大厦18层中睿信息 Fax:020-38931912 专业 Professional
深圳:深圳市福田区车公庙有色金属大厦509~510 Tel:0755-25855012 诚信 Integrity
所有权声明:PMI, PMP, Project Management Professional, PMI-ACP, PMI-PBA和PMBOK是项目管理协会(Project Management Institute, Inc.)的注册标志。
版权所有:广州中睿信息技术有限公司 粤ICP备13082838号-2