一、jQuery $(document).ready()执行顺序-------------二、jquery $(document).ready() 与window.onload的区别

jQuery $(document).ready()执行顺序

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>

执行完页面打印出来的顺序是:
这里写图片描述

jquery $(document).ready() 与window.onload的区别
1.执行时间

window.onload必须等到页面内包括图片的所有元素加载完毕后才能执行。
$(document).ready()是DOM结构绘制完毕后就执行,不必等到加载完毕。

2.编写个数不同

window.onload不能同时编写多个,如果有多个window.onload方法,只会执行一个
$(document).ready()可以同时编写多个,并且都可以得到执行

3.简化写法

window.onload没有简化写法
(document).ready(function()) (function(){});
这里写图片描述

另外,需要注意一点,由于在 (document).ready()DOMhtmlDOM使Jqueryload()Load()onloadwindow()Jquery (window).load(function (){
// 编写代码
});等价于 JavaScript 中的以下代码
Window.onload = function (){
// 编写代码
}
转自 http://www.cnblogs.com/haichuan3000/articles/2128889.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值