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

依然范特西╮ 提交于 2019-11-30 14:28:50
$(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(){});

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 :)

TheMonkeyMan

$(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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!