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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…