The ready
method was implemented in jQuery to execute code when the DOM is fully loaded. Since it executes the given function when all DOM elements are available, you can be sure that trying to access or manipulate elements will work.
Before jQuery 3.0, the typical usage with a anonymous function looked like this:
$(document).ready(function() {
// Handler for .ready() called.
});
jQuery 3.0 ready() Changes
Before the release of version 3, there were several ways you could call the ready
method:
- on the document element:
$(document).ready(handler);
- on an empty element:
$().ready(handler);
- or directly (i.e. not on a specific element):
$(handler);
All above named variants are functionally equivalent. The specified handler will be called when the DOM is fully loaded, no matter on which element it was called. In other words, calling it on an image element $("img")
versus the document element doesn't indicate that the callback is fired when the specified element is loaded. Instead, it will be called when the entire DOM is fully loaded.
In jQuery 3.0, all other syntax methods except $(handler);
are deprecated. The official justification is:
This is because the selection has no bearing on the behavior of the
.ready()
method, which is inefficient and can lead to incorrect assumptions about the method's behavior.
Difference Between the Ready and Load Events
The ready
event is fired when the DOM is fully loaded and accesses to elements are safe. The load
event, on the other hand, is fired after the DOM and all assets have loaded.
The load event can be used as follows:
Continue reading %Quick Tip: Replace jQuery’s Ready() with Plain JavaScript%
by Julian Motz via SitePoint
No comments:
Post a Comment