$ (document) .ready () - how is it executed?
$(document).ready()
- How is it done? Will the cursor wait at this part of the line to execute the code after the DOM has been created OR will this method be executed as an event handler after the browser has created the DOM?
What if the image is not loaded but $(document).ready()
is executed to read the image attribute src
to assign some other local variable after the DOM is built?
source to share
This is an event handler and it doesn't wait for everything to load. It only waits until the DOM has been constructed and transformed ready
. From the docs :
Although JavaScript provides a load event to execute code when the page is displayed, this event is not fired until all assets, such as images, have been fully retrieved. In most cases, the script can be run as soon as the DOM hierarchy is fully built. The handler passed to .ready () is guaranteed to execute after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it is important to reference external style sheets or inject style elements before referencing scripts.
The code behind it is pretty simple, actually. It just waits until it document.body
is available (not null):
function (wait) {
// Either a released hold or an DOMready/load event and not yet ready
if ((wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady)) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if (!document.body) {
return setTimeout(jQuery.ready, 1);
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if (wait !== true && --jQuery.readyWait > 0) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith(document, [jQuery]);
// Trigger any bound ready events
if (jQuery.fn.trigger) {
jQuery(document).trigger("ready").unbind("ready");
}
}
}
From http://james.padolsey.com/jquery/#v=1.6.2&fn=jQuery.ready
source to share