Daily Tip : Difference between $(document).ready and $(window).load in jQuery
This is the first of many “daily tip” posts, in which i will explain the difference between $(document).ready() and $(window).load(), and when to use which.
$(document).ready(function(){
//code here
});
The code above is used almost every time when we work with jQuery. Of course there are many different types of this, like $(function(){ //code here }) and some more. But i will leave that for another daily tip. This code is used when we want to initialize our jQuery codes after the DOM is ready.
So what do we need $(window).load() for ?
Sometimes you want to manipulate pictures. For example you want to verticaly and horizontaly align a picture and you need to get the width and height of the picture in order to do that. With $(document).ready() you won’t be able to do that if the visitor doesn’t have the image already loaded, in which case you need to initialize the jquery alignment function when the image finishes loading. That’s where we use…
$(window).load(function(){
//initialize after images are loaded
});
Related posts:
- Defer Load jQuery Plugin
- Verticaly center an image inside a div
- jQuery and Ajax :) the simple designer way
- How to make a completely reusable jquery modal window
- Automatic input field focus on page load
Slobodan Kustrimovic
This author has yet to fill his BIO.
Did you absolutely LOVE this article... share it!
Comments
ok, thank’s for the tip..
i just know the different beetwen $(document).ready and $(window).load
I was using $(window).ready and wondering why it wasn’t working… Thanks for the tip!
Thanks ,this is exactly what i was looking for.
Thanks mate, I’m certainly putting this into a practise.. right now
Leave your own!