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?
相关问题
- How to fix IE ClearType + jQuery opacity problem i
- jQuery add and remove delay
- Include empty value fields in jQuery .serialize()
- Disable Browser onUnload on certain links?
- how to get selected text from iframe with javascri
$(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 beforewindow
's load event.Note that
$(document).ready()
is the preferred way of binding something todocument
load; there are a couple other ways of doing it like the one you showed, but that's preferred.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:
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:
Now,
$(window).load(function(){});
is equal towindow.onload = function(){ alert("welcome"); }
And,
$(function(){});
is a shortcut to$(document).ready(function(){ });
I think , this clears everything :)