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

I used $(window).load(function(){}); for my projects, until somewhere I saw that someone said that we can just use $(function(){}); , and they will be executed the same way.
But now that I have more experience, I noticed that they are not identical. I noticed that the first piece hit a bit after the second piece of code.
I just want to know what is the difference?

+6
source share
4 answers
 $(document).ready(function(){}) 

It will wait for the document to load (the DOM tree is loading), and not until the entire window is loaded. for example, it will not wait for the full download of images, css or javascript. When the DOM is loaded by all HTML components and event handlers, the document is ready for processing, and then $ (document) .ready () will complete

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

This is the wait for the entire window to load. When the whole page loads, only $ (window) .load () ends. Therefore, it is obvious that $ (document) .ready (function () {}) ends before $ (window) .load (), because it takes more time to fill in components (for example, images, css), and then the tree just loads DOM

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

+10
source

From jQuery docs .

The first thing most Javascript programmers do is to add code to their program similar to this:

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

Inside this code is the code that you want to run immediately when the page loads. However, it is unclear that Javascript code does not run until all images have been loaded (including banner ads). The reason for using window.onload in the first place is because the HTML document is not finished when you first try to run your code.

To work around both problems, jQuery has a simple statement that checks the document and waits until it is ready for management, as a finished event:

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

Now

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

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

I think it clears everything :)

+4
source

$(window).load in my experience, waits until all downloaded images are loaded before launch, where $(function() {}); will have the same behavior as $(document).ready(function() {});

Please correct me if I am wrong.

+2
source

The second parameter / was a shortcut for $(document).ready() , which should be executed before the window load event.

Note that $(document).ready() is the preferred way to bind something to the loading of document ; There are a couple of other ways to do this, like the one you showed, but it is preferable.

0
source

Source: https://habr.com/ru/post/917530/


All Articles