What's the difference between `$(window).load(function(){})` and `$(function(){})`

19.4k views Asked by At

I was using $(window).load(function(){}); for my projects until somewhere I saw that somebody said we could just use $(function(){}); and they would perform identically.
But now that I have more experience I have noticed that they are not identical. I noticed that the first piece kicks in a little bit after the second piece of code.
I just want to know what's the difference?

4

There are 4 answers

0
prashant On BEST ANSWER
$(document).ready(function(){})

will wait till the document is loaded(DOM tree is loaded) and not till the entire window is loaded. for example It will not wait for the images,css or javascript to be fully loaded . Once the DOM is loaded with all the HTML components and event handlers the document is ready to be processed and then the $(document).ready() will complete

$(window).load(function(){});

This waits for the entire window to be loaded. When the entire page is loaded then only the $(window).load() is completed. Hence obviously $(document).ready(function(){}) finishes before $(window).load() because populating the components(like images,css) takes more time then just loading the DOM tree.

So $(function(){}); cannot be used as a replacement for $(window).load(function(){});

1
TheMonkeyMan On

$(window).load from my experience waits until everything including images is loaded before running where as $(function() {}); has the same behaviour as $(document).ready(function() {});

Please someone correct me if I am wrong.

0
ajm On

The second is/was a shortcut for $(document).ready(), which should run before window's load event.

Note that $(document).ready() is the preferred way of binding something to document load; there are a couple other ways of doing it like the one you showed, but that's preferred.

3
Jashwant On

From the jQuery docs itself.

The first thing that most Javascript programmers end up doing is adding some code to their program, similar to this:

window.onload = function(){ alert("welcome"); }

Inside of which is the code that you want to run right when the page is loaded. Problematically, however, the Javascript code isn't run until all images are finished downloading (this includes banner ads). The reason for using window.onload in the first place is that the HTML 'document' isn't finished loading yet, when you first try to run your code.

To circumvent both problems, jQuery has a simple statement that checks the document and waits until it's ready to be manipulated, known as the ready event:

$(document).ready(function(){
   // Your code here
 });

Now,

$(window).load(function(){}); is equal to window.onload = function(){ alert("welcome"); }

And, $(function(){}); is a shortcut to $(document).ready(function(){ });

I think , this clears everything :)