原生js实现jQuery的ready方法

本文详细对比了window.onload与$(document).ready的区别,包括执行时机、编写数量及简化写法等,并介绍了如何用原生JS实现jQuery的ready方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#window.onload

From the MDN, window.onload:

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

window.onload在页面的DOM加载完成,所有的图片、子frame等所有的元素都加载完成的时候才会触发。

#$(document).ready

From the jQuery API documentation, .ready( handler ):

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. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

$(document).ready方法发生在DOM树构造完成,而不会等到其余的所有的元素都加载完成。其实说白了就是ready方法在onload之前发生,一般发生在DOM树构造完成的时候。

具体一些,可以从以下几方面对比$(document).readywindow.onload的区别:

  1. 执行时间
    window.onload必须等到页面内包括图片的所有元素加载完毕后才能执行。
    $(document).ready是DOM结构绘制完毕后就执行,不必等到图片等资源加载完成后才执行。
  2. 编写个数不同
    window.onload不能同时编写多个,如果有多个window.onload方法,后面会覆盖前面,并且只会执行一个onload方法。
    $(document).ready可以同时编写多个,并且都可以得到执行。
window.onload = function(){
    console.log("window.onload event1");
}
window.onload = function(){
    console.log("window.onload event2");
}
$(document).ready(function(){
    console.log("jquery ready event1");
})
$(document).ready(function(){
    console.log("jquery ready event2");
})

执行结果如下:
jqueryready-windowonload.png

确实可以看出ready先于onload事件。并且onload只能有一个,后面覆盖前面,而ready恰好相反。

  1. 简化写法
    window.onload没有简化写法。
    $(document).ready(function(){})可以简写成$(function(){});
    在一些开发中,大多数时候,第一行写的是:
$(document).ready(function(){
    //coding...
});

这个时候,不一定要等所有的图片加载完毕,就可以执行一些方法,不过有些时候,必须要等所有的元素都加载完毕,才可以执行一些方法,比如说,部分图片或者什么其他方面还没有加载好,这个时候,点击某些按钮,会导致出现意外的情况,这个时候,就需要用到$(window).load方法:

$(window).load

$(window).loadwindow.onload其实没什么大的区别

"This method is a shortcut for .on( "load", handler )."

jquery API中提到$(window).load方法是$(window).on('load',handler)的shortcut,而且$(window).on('load',handler)相当于window.onload方法

$(window).load(function (){  
    // coding
});  
//等价于 JavaScript 中的以下代码  
window.onload = function (){  
    // coding
} 

如果真要说区别的
$(window).load(handler)可以用多次使用,并且handler都会依次执行。但是window.onload就不行,就像上面介绍的一样,window.onload = handler后面的hanlder会覆盖之前的handler。

$(window).load(function() {  
    $("#btn-upload").click(function(){
        //coding upload
    });  
});  

注意:由于在$(document).ready()方法内注册的事件,只要 DOM 就绪就会被执行,因此可能此时元素的关联文件未下载完。例如与图片有关的 html 下载完毕,并且已经解析为 DOM 树了,但很有可能图片还没有加载完毕,所以获取图片的高度和宽度这样的属性此时不一定有效。要解决这个问题,可以使用 jquery 中另一个关于页面加载的方法 ---load() 方法。 Load() 方法会在元素的 onload 事件中绑定一个处理函数。如果处理函数绑定给 window 对象,则会在所有内容 ( 包括窗口、框架、对象和图像等 ) 加载完毕后触发,如果处理函数绑定在元素上,则会在元素的内容加载完毕后触发。

用原生JS实现jQuery的ready方法

那么,对于某些特殊需求,不希望使用jQuery,但又想实现jQuery的ready方法。该如何用原生JS实现jQuery的ready方法呢?下面是其中之一的做法::

function ready(fn){  
    if(document.addEventListener){      
        //标准浏览器  
        document.addEventListener('DOMContentLoaded',function(){  
            //注销事件,避免反复触发  
            document.removeEventListener('DOMContentLoaded',arguments.callee,false); 
            //执行函数   
            fn();
        },false);  
    }else if(document.attachEvent){     
        //IE浏览器  
        document.attachEvent('onreadystatechange',function(){  
            if(document.readyState=='complete'){  
                document.detachEvent('onreadystatechange',arguments.callee);  
                //执行函数   
                fn();  
            }  
        });  
    }  
}

下面用一段代码验证ready函数的正确性:

window.onload = function(){
    console.log("window.onload event");
}
ready(function(){
    console.log('window ready event')
})

执行结果如下:
ready

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值