Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
148
rated 0 times [  154] [ 6]  / answers: 1 / hits: 61031  / 11 Years ago, thu, february 13, 2014, 12:00:00

Are there any advantages of using the Jquery ready() function over window.onload?



// Jquery ready
$(document).ready(function() {

});

// window.onload
window.onload = function () {

}

More From » jquery

 Answers
14

Depends on what you want to do.




  • jQuery ready will run your code when the HTML is all ready, but before images and other resources have finished. This is the earliest possible time that you can change the DOM with JavaScript, so it's widely used. (In modern browsers it's replaced by the native event DOMContentLoaded).

  • window.onload (the load event) runs after everything has finished loading. Images, Flash, and some scripts, but usually not stylesheets. Use this for code that should run only when the page won't change any more.



Also, with window.onload you can only attach one listener, but you can attach as many as you want with jQuery ready. To attach more than one event on window.onload, use addEventListener:



window.addEventListener('load', function () {

}, false);

[#72556] Tuesday, February 11, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;