$(document).ready vs $(window).load vs window.onload

本文详细解释了jQuery中$(document).ready、$(window).load与window.onload三种页面加载事件的区别及应用场景。通过具体示例展示了不同事件触发时机的特点,帮助开发者更好地理解和使用这些事件。

原文地址: $(document).ready vs $(window).load vs window.onload

$(document).ready

We execute our code when DOM is ready except images.

 1 //call type 1
 2 $(document).ready(function() {
 3 /** work when all HTML loaded except images and DOM is ready **/
 4 // your code
 5 });
 6  
 7 //call type 2
 8 $(function() {
 9 /** work when all HTML loaded except images and DOM is ready **/
10 //your code
11 });
12  
13 //call type 3
14 $(document).on('ready', function(){
15 /** work when all HTML loaded except images and DOM is ready **/
16 //your code
17 });
18  
19 //call type 4
20 jQuery(document).ready(function(){
21 /** work when all HTML loaded except images and DOM is ready **/
22 //your code
23 });

$(window).load

It is work when all DOM is ready including images so it is useful when on document load we want to work with images.

1 $(window).load(function() {
2 /** this is come when complete page is fully loaded, including all frames, objects and images **/
3 });

window.onload

The onload event is a standard event in the DOM, while above two are specific to jQuery . this is also same functionality like $(window).load but  window.onload is the built-in JavaScript event.The onload event occurs when an object has been loaded.like if we take a example of image and call onload event in image tag then it will call when image will load .generally we use it in body tag.

In HTML

1 <element οnlοad="myFunction"></element>

In JS

1 object.οnlοad=function(){/**your desire code**/};// here object can be window,body and etc

1)  Here  alert “call on body load” call  immediately after body has been loaded

1 // In HTML
2 <!-- on body onload call myFunction -->
3 <body οnlοad="myFunction()">
4 
5 //In JavaScript
6 // myFunction() which will call on body load
7 function myFunction(){
8    alert("call on body load");
9 }

2)  Here  alert “call on image load” call  immediately after image has been loaded

1 // In HTML
2 <!-- on image onload call myImageFunction() -->
3 <img src="image path src" οnlοad="myImageFunction()">
4 
5 // // myFunction() which will call on image load
6 function myImageFunction(){
7    alert("call on image load");
8 }

 window.onload  Examples

The function 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, scripts, links and sub-frames have finished loading.

1 window.onload = function() {
2   init();
3   doSomethingElse();
4 };

 以上です。

转载于:https://www.cnblogs.com/hzj680539/p/5051776.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值