What are the differences between JavaScript's window.onload
and jQuery's $(document).ready()
method?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
A little tip:
Always use the
window.addEventListener
to add an event to window. Because that way you can execute the code in different event handlers .Correct code:
Invalid code:
This is because onload is just property of the object, which is overwritten.
By analogy with
addEventListener
, it is better to use$(document).ready()
rather than onload.window.onload
is a JavaScript inbuilt function.window.onload
trigger when the HTML page loaded.window.onload
can be written only once.document.ready
is a function of the jQuery library.document.ready
triggers when HTML and all JavaScript code, CSS, and images which are included in the HTML file are completely loaded.document.ready
can be written multiple times according to requirements.When you say
$(document).ready(f)
, you tell script engine to do the following:$
and select it, since it's not in local scope, it must do a hash table lookup, which may or may not have collisions.ready
of selected object, which involves another hash table lookup into the selected object to find the method and invoke it.In the best case, this is 2 hash table lookups, but that's ignoring the heavy work done by jQuery, where
$
is the kitchen sink of all possible inputs to jQuery, so another map is likely there to dispatch the query to correct handler.Alternatively, you could do this:
which will
onload
is a property or not by doing a hash table lookup, since it is, it is called like a function.In the best case, this costs a single hash table lookup, which is necessary because
onload
must be fetched.Ideally, jQuery would compile their queries to strings that can be pasted to do what you wanted jQuery to do but without the runtime dispatching of jQuery. This way you have an option of either
eval
.window.onload: A normal JavaScript event.
document.ready: A specific jQuery event when the entire HTML have been loaded.
One thing to remember (or should I say recall) is that you cannot stack
onload
s like you can withready
. In other words, jQuery magic allows multipleready
s on the same page, but you can't do that withonload
.The last
onload
will overrule any previousonload
s.A nice way to deal with that is with a function apparently written by one Simon Willison and described in Using Multiple JavaScript Onload Functions.