Is there a way of checking if the HTML DOM element/s for a given selector/element are ready yet using jQuery or JavaScript?
Looking at the jQuery api for the ready
-------- 2016 --------
I came with a possible solution using promises that maybe can help somebody else, I'm using jquery
cause I'm lazy :P.
Pretty much is waiting until the dom
exist and then execute the resolve function in the promise:
var onDomIsRendered = function(domString) {
return new Promise(function(resolve, reject) {
function waitUntil() {
setTimeout(function() {
if($(domString).length > 0){
resolve($(domString));
}else {
waitUntil();
}
}, 100);
}
//start the loop
waitUntil();
});
};
//then you can use it like
onDomIsRendered(".your-class-or-id").then(function(element){
console.log(element); //your element is ready
})
Following piece of code worked for me !
<print condition="true"></print>
<script>
$('print').load('#',function(){
alert($(this).attr('condition'));
});
</script>
The answer is probably no. from a browser perspective it is probably a bad design and might not even be possible to allow something like this.
for dynamically inserted elements after the DOM is ready there is the dom event - DOMNodeInserted - that you can use. you can also use the jquery live as mentioned above that probably uses the same event.
Yes, it is possible: and while it's not native, it is pretty easy to impliment. Just trigger a custom event after the node you're looking for is loaded into the DOM.
Note: I'm writing this in jQuery, which means you have to include jQuery early in the load process, which is a no-no performance wise. That being said, if you already have jQuery high up in your document or if DOM construction is taking a hella long time for you, this might be worthwhile. Otherwise, you're free to write this in vanilla JS to skip the $ dependency.
<!DOCTYPE HTML>
<html><head><title>Incremental DOM Readyness Test</title></head><body>
<script src="/js/jquery.js"></script>
<script>
jQuery(document.body).on("DOMReady", "#header", function(e){
var $header = jQuery(this);
$header.css({"background-color" : "tomato"});
}).on("DOMReady", "#content", function(e){
var $content = jQuery(this);
$content.css({"background-color" : "olive"});
});
</script>
<div class="header" id="header">
<!-- Header stuff -->
</div>
<script>jQuery("#header").trigger("DOMReady");</script>
<div class="content" id="content">
<!-- Body content. Whatever is in here is probably really slow if you need to do this. -->
</div>
<script>jQuery("#content").trigger("DOMReady");</script>
</body></html>
Edit 2012
The live
method is deprecated as of jQuery 1.7.0. The .on() event is now recommended for attaching event handlers. This replaces .bind(), .delegate(), and .live().
See the docs: http://api.jquery.com/on/
Original Answer
i think jQuery .live() event might be what you're looking for.