search
HomeWeb Front-endFront-end Q&AWhat is the difference between jquery $(document).ready() and onload

Difference: There is no simplified writing method for window.onload. It must wait until all elements in the page, including pictures, are loaded before it can be executed. And "$(document).ready()" can be abbreviated as "$(function(){})", which is executed after the DOM structure is drawn, without having to wait until it is loaded.

What is the difference between jquery $(document).ready() and onload

Recommended tutorial: jquery video tutorial

##jquery $(document).ready( ) and window.onload

1. Execution time

window.onload must wait until all elements in the page, including images, are loaded. 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

You cannot write multiple window.onloads at the same time. If there are multiple window.onload methods, only one will be executed

$(document).ready() can be written multiple times at the same time, and all of them can be executed

3. Simplified writing method

There is no simplified writing method for window.onload

$(document).ready(function(){}) can be abbreviated as $(function(){});

Instructions:

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.

$(document).ready() method and window.onload method have similar functions, but there are differences in execution timing. The window.onload method is executed after all elements in the web page (including the elements' associated files) are completely loaded into the browser, that is, JavaScript can only access any element in the web page at this time. The event handler registered through the $(document).ready() method in jQuery can be called when the DOM is completely ready. At this point, all elements of the web page are accessible to jQuery, but this does not mean that the files associated with these elements have been downloaded.

For example, there is a large photo gallery website that adds certain behaviors to all pictures in the web page, such as hiding or displaying the picture after clicking on it. If the window.onload method is used, the user must wait until each image is loaded before proceeding. If you use the $(document).ready() method in jQuery to set it up, you can operate it as soon as the DOM is ready, without waiting for all images to be downloaded. Obviously, parsing a web page into a DOM tree is much faster than loading all associated files in the web page.

Another thing to note is 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 () {
    //编写代码
})

Equivalent to the following code in JavaScript:

window.onload = function () {
    //编写代码
}

Assume there are two functions in the web page, the JavaScript code is as follows:

function one() {
    alert("one");
}
function two() {
    alert("two");
}

When the web page is loaded Finally, the one function and the two function are called respectively through the Javascript code:

window.onload = one;
window.onload = two;

However, when the code is run, it is found that only the string "two" dialog box pops up.

The reason why the string "one" dialog box cannot be popped up is that JavaScript's onload event can only save a reference to one function at a time. It will automatically overwrite the previous function with the later function, so it cannot be used in the existing function. Add new behavior to the behavior.

In order to achieve the effect of sequential triggering of two functions, it can only be achieved by creating a new JavaScript method. The JavaScript code is as follows:

window.onload = function () {
    one();
    two();
}

Although the code written in this way can solve certain problems, But it still cannot meet certain needs. For example, if there are multiple JavaScript files, each file needs to use the window.onload method. In this case, it will be very troublesome to write code using the method mentioned above. You can refer to the Javascript shared onload event, and jQuery's $(document).ready() method can handle these situations well. Each call to the $(document).ready() method will append new behavior to the existing behavior. Behaviors, these behavior functions will be executed sequentially according to the order of registration. For example, the following jQuery code:

function one() {
    alert("one");
}
function two() {
    alert("two");
}
$(document).ready(function () {
    one();
});
$(document).ready(function () {
    two();
})

After running the code, the string "one" dialog box will pop up, and then the string "two" dialog box will pop up

For more programming-related knowledge, please visit:

Programming Teaching! !

The above is the detailed content of What is the difference between jquery $(document).ready() and onload. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

CSS ID and Class: common mistakesCSS ID and Class: common mistakesMay 13, 2025 am 12:11 AM

IDsshouldbeusedforJavaScripthooks,whileclassesarebetterforstyling.1)Useclassesforstylingtoallowforeasierreuseandavoidspecificityissues.2)UseIDsforJavaScripthookstouniquelyidentifyelements.3)Avoiddeepnestingtokeepselectorssimpleandimproveperformance.4

What is thedifference between class and id selector?What is thedifference between class and id selector?May 12, 2025 am 12:13 AM

Classselectorsareversatileandreusable,whileidselectorsareuniqueandspecific.1)Useclassselectors(denotedby.)forstylingmultipleelementswithsharedcharacteristics.2)Useidselectors(denotedby#)forstylinguniqueelementsonapage.Classselectorsoffermoreflexibili

CSS IDs vs Classes: The real differencesCSS IDs vs Classes: The real differencesMay 12, 2025 am 12:10 AM

IDsareuniqueidentifiersforsingleelements,whileclassesstylemultipleelements.1)UseIDsforuniqueelementsandJavaScripthooks.2)Useclassesforreusable,flexiblestylingacrossmultipleelements.

CSS: What if I use just classes?CSS: What if I use just classes?May 12, 2025 am 12:09 AM

Using a class-only selector can improve code reusability and maintainability, but requires managing class names and priorities. 1. Improve reusability and flexibility, 2. Combining multiple classes to create complex styles, 3. It may lead to lengthy class names and priorities, 4. The performance impact is small, 5. Follow best practices such as concise naming and usage conventions.

ID and Class Selectors in CSS: A Beginner's GuideID and Class Selectors in CSS: A Beginner's GuideMay 12, 2025 am 12:06 AM

ID and class selectors are used in CSS for unique and multi-element style settings respectively. 1. The ID selector (#) is suitable for a single element, such as a specific navigation menu. 2.Class selector (.) is used for multiple elements, such as unified button style. IDs should be used with caution, avoid excessive specificity, and prioritize class for improved style reusability and flexibility.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function