jQuery.ready() equivalent event listener on elements?

István Pálinkás picture István Pálinkás · Oct 14, 2013 · Viewed 25.8k times · Source

I am using jQuery JavaScript library. I like the event listener ready on $(document) that fires when the DOM is set up.

( Pretty similar to .onload but without external sources )

I would find it very useful, if there was an event listener which has a very similar behavior to this, but fires when an element is fully loaded. (f.e.: Picture, a Div with an extremely long text content, such )

I would appreciate both jQuery or JavaScript methods.

Answer

jfriend00 picture jfriend00 · Oct 14, 2013

There is no event fired when an arbitrary DOM element such as a <div> becomes ready. Images have their own load event to tell you when the image data has been loaded and has been rendered and a few other special types of elements have an event. But, regular DOM elements do not have such an event.

If you want javascript code to be executed as soon as an arbitrary DOM element is ready, the only way to do that is to place a function call in an inline script right after that DOM element. At that point that DOM element will be ready, but the rest of the DOM afterwards may not yet be ready. Otherwise, the script can be placed at the end of the document or the script can be fired when the whole document is ready.

Here are the existing load events expressed in jQuery form (these can all be done in plain JS too):

// when a particular image has finished loading the image data
$("#myImage").load(fn);

// when all elements in the document are loaded and ready for manipulation
$(document).ready(fn);

// when the DOM and all dynamically loaded resources such as images are ready
$(window).load(fn);

In jQuery, you can also dynamically load content and be notified when that content has been loaded using the .load() method like this:

$( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});

Internally, this just does an ajax call to fetch the data and then calls the callback after the data has been retrieved by ajax and then inserted into the document. It isn't a native event.


If you have some code that is dynamically loading elements in to the DOM and you want to know when those DOM elements are present, then the best way to know when they are ready is to have the code that adds them to the DOM create some sort of event to tell you when it's ready. This prevents battery wasting polling efforts trying to find out if the element is now in the DOM.

It is also possible to use the DOM MutationObserver to see when specific types of changes have been made to the DOM.