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 wich has a very similar behaviour 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.
All elements (including
div
andimg
) are ready as soon as DOMReady fires - that's what it means.However, you can use the
load()
event to run some code when animg
tag has fully loaded the image in it'ssrc
attribute:There is no event fired when an arbitrary DOM element such as a
<div>
becomes ready. Images have their ownload
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):
In jQuery, you can also dynamically load content and be notified when that content has been loaded using the
.load()
method like this: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.
jQuery don't have it, but we can create our own onDomElementIsReady, Tools:
jQuery
,ES6
,Promise
andInterval
(I'm lazy, but you can get the idea)We will wait until the element existed on the DOM and as soon is available we will resolve the
promise
result.NOTE: To improve this we should add a timer that
reject
the promise if the DOM element never exists.