Home Web Front-end JS Tutorial The difference between jquery $(document).ready() and window.onload_jquery

The difference between jquery $(document).ready() and window.onload_jquery

May 16, 2016 pm 06:38 PM
jquery

1. Execution time

​ ​ ​ window.onload must wait until all elements in the page, including images, are loaded before it can be executed.
​​​​ $(document).ready() is executed after the DOM structure is drawn, without having to wait until it is loaded.

2. The number of writes is different

Window.onload cannot write multiple at the same time. If there are multiple Window.Onload methods, only one
​​​​​ $(document).ready() can be written multiple times at the same time, and all can be executed

3. Simplified writing

There is no simplified writing method for window.onload
            $(document).ready(function(){}) can be abbreviated as $(function(){});

In my previous development, I usually used javascript, and I always used jquery mode. That is, most of the time, the first line is:

Copy code The code is as follows:

$(document).ready(function(){
...
});

At this time, you don’t have to wait for all js and images to be loaded before you can execute some methods, but sometimes, you have to wait for all


When all elements are loaded, some methods can be executed. For example, some pictures or other aspects have not been loaded yet. At this time, clicking some buttons will cause unexpected situations. At this time,

Need to use:

Copy code The code is as follows:

$(window).load(function() {
$("#btn-upload").click(function(){ //For example:
uploadPhotos();
});
});

The following is the reproduced content,
Several reasons to use $(window).load(function(){...}) instead of body.onload()
First of all, they are executed after all elements of the page (including html tags and all referenced images, Flash and other media) are loaded. This is what they have in common.

Reason 1 for not using body.Onload():

If we want to load multiple functions at the same time, we must write like this

looks extremely ugly. If we use $(window).load() we can load multiple functions like this

Copy code The code is as follows:

$(window).load(function() {
alert("hello, this is jQuery!");
});
$(window).load(function() {
alert("hello, I am also jQuery");
});

Written like this, it will execute these two functions from top to bottom, and it looks much prettier.

Reason 2 for not using body.Onload():

Using body.Onload() cannot completely separate js and html. This is a very serious problem.

In addition, using $(window).load(function(){...}) and body.onload() has the same problem, because as mentioned at the beginning, they both need to wait until all the content of the page is available

It is executed after loading is complete, but if the network speed is relatively slow, it often takes a long time to load a page (ranging from a few seconds to more than ten seconds, or even longer...), so we often

There will be situations where the page has not been fully loaded and the user is already operating the page, so the effect of the page will be different from what we expected,

So here I recommend using $(document).ready(function(){}), or abbreviated as $(function(){}), because it will be executed after the DOM element of the page is loaded,

No need to wait for images or other media to download.

But sometimes we do need to wait until everything on the page is loaded before executing the function we want to execute, so should we use $(window).load(function(){...}) or

The use of $(function(){}) often requires different choices based on specific needs.

Finally, attach a piece of jQuery code that is executed before all DOM elements are loaded

Copy code The code is as follows:


Haha, sometimes we also have this need!

Take the browser loading a document as an example. After the page is loaded, the browser will add events to the DOM elements through Javascript. In regular Javascript code, the window.onload method is usually used, while in Jquery, the $(document).ready() method is used. The $(document).ready() method is the most important function in the event module, which can greatly improve the speed of web applications.

window.load $(document).ready()
Execution timing: You must wait for all content in the webpage to be loaded (including images) before execution. Execution occurs after all DOM structures in the webpage are drawn. It is possible that the content associated with the DOM element has not been loaded.
Number of items to write You cannot write multiple
at the same time The following code does not execute correctly:

window.onload = function(){ 
  alert(“text1”); 
}; 
window.onload = function(){ 
  alert(“text2”); 
}; 
Copy after login


Only the second result is output. Multiple
can be written at the same time. The following code executes correctly:

$(document).ready(function(){ 
  alert(“Hello World”); 
}); 
$(document).ready(function(){ 
  alert(“Hello again”); 
}); 
Copy after login

The result is output twice
Simplified writing None

 $(function(){ 
  // do something 
}); 
Copy after login

In addition, it should be noted that since the event registered in the $(document).ready() method will be executed as long as the DOM is ready, the associated file of the element may not be downloaded at this time. For example, the html related to the image has been downloaded and parsed into a DOM tree, but it is very likely that the image has not been loaded yet, so attributes such as the height and width of the image may not be valid at this time. To solve this problem, you can use another page loading method in Jquery --- the load() method. The Load() method binds a handler function to the element's onload event. If the handler function is bound to the window object, it will be triggered after all content (including windows, frames, objects, images, etc.) is loaded. If the handler function is bound to an element, it will be triggered after the content of the element is loaded.
The Jquery code is as follows:
$(window).load(function (){
//Write code
}); Equivalent to the following code in JavaScript
Window.onload = function (){
//Write code
}

————————————————————————————

When I recently changed a page embedded in a frame, I used jquery for effect, and the page itself was also bound to the onload event. After the modification, the test runs normally and smoothly under Firefox, but it takes more than ten seconds for the jquery effect to appear under IE, and the day lily is cold.

At first I thought it was conflicting with the onload method. A common saying on the Internet is that $(document).ready() is executed after the page DOM parsing is completed, and the onload event is executed after all resources are prepared. In other words, $(document).ready() is executed after the page DOM parsing is completed. Executed before onload, especially when the page pictures are larger and more, the time difference may be larger. But on my page, the picture has been displayed for more than ten seconds, but the jquery effect has not yet appeared.

Try deleting the onload loading method, but the result is still the same. It seems that there is no need to use $(document).ready() to write the original onload event binding. So what is the reason why Firefox works but IE does? Then debugging, I found that the originally bound onload method under IE was executed before the content of $(document).ready(), while Firefox executed the content of $(document).ready() first, and then executed the original onload method. . This doesn’t seem to be completely consistent with what’s said online. Haha, it’s interesting. It seems to be getting closer to the truth.

Look through the source code of jquery to see how $(document).ready() is implemented:

if ( jQuery.browser.msie && window == top ) (function(){ 
if (jQuery.isReady) return; 
try { 
document.documentElement.doScroll("left"); 
} catch( error ) { 
      setTimeout( arguments.callee, 0 ); 
       return; 
    } 
   // and execute any waiting functions 
   jQuery.ready(); 
})(); 
jQuery.event.add( window, "load", jQuery.ready ); 
Copy after login

The result is very clear. Only when the page is not embedded in a frame, IE, like Firefox, first executes the content of $(document).ready(), and then executes the original onload method. For the page embedded in the frame, it is only bound to the load event for execution, so naturally it is the turn after the original onload binding method is executed. And this page happens to have a resource that is inaccessible in the test environment, and the delay of more than ten seconds is exactly the time difference it amplifies.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

In-depth analysis: jQuery's advantages and disadvantages In-depth analysis: jQuery's advantages and disadvantages Feb 27, 2024 pm 05:18 PM

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? How to tell if a jQuery element has a specific attribute? Feb 29, 2024 am 09:03 AM

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles