27

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 function it looks like it can only be used with the document object. If ready cannot be used for this purpose is there another way of doing this?

e.g.

 $('h1').ready(function()
{
 //do something when all h1 elements are ready
});

Obviously I could use

$(document).ready(function()
{
 //do something when all h1 elements are ready
});

But if all the h1's load first then the code specific to h1 elements will only execute after the whole document is ready even though it could actually execute earlier.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
8bitme
  • 897
  • 2
  • 16
  • 24
  • why do you want to execute it earlier than the document is ready? – nWorx Jul 04 '11 at 13:07
  • 1
    may I ask, why do you need this ? – Anas Nakawa Jul 04 '11 at 13:07
  • I don't think that having your script execute as earlier as it can will improve the overall performance of your website, because generally, JavaScript execution blocks other content from loading. Your best bet is to use `$(document).ready`. – FishBasketGordo Jul 04 '11 at 13:08
  • @nWorx/anasnakawa I want to fire off some AJAX events when certain HTML elements are ready but other elements like tables force the ready function to wait until they are finished loading – 8bitme Jul 04 '11 at 13:43
  • A bit strange to see how many wonder about the use of this. There are plenty of JS based controls that are purely created at runtime. Which means that the document-ready mechanism will be useless. If you create an element with createElement(), the element wont be populated (e.g prototype setup) until after the calling function exits. This causes issues when you have a traditional constructor/destructor pattern and a VMT (which is common when compiling from C++, Delphi etc etc). – Jon Lennart Aasenden Apr 27 '20 at 09:50

5 Answers5

6

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.

Chris Baker
  • 49,926
  • 12
  • 96
  • 115
Ruslan
  • 9,927
  • 15
  • 55
  • 89
4

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>
Ansikt
  • 1,442
  • 11
  • 13
2

-------- 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
})
ncubica
  • 8,169
  • 9
  • 54
  • 72
  • How about when the element disappears from DOM, but can reappear later on? How would I catch this? – paskl Nov 11 '16 at 17:56
1

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.

0

Following piece of code worked for me !

<print condition="true"></print> 

   <script>
    $('print').load('#',function(){
        alert($(this).attr('condition')); 
     });
   </script>
N_E
  • 743
  • 10
  • 16