jQuery – Wait for a given DOM element when is ready and rendered

The first solution :

var onReadyDomElement = function(element) {
  return new Promise(function(callback, reject) {
    function checkAgain() {
      setTimeout(function() {
        if(jQuery(element) !== null ){
          callback(jQuery(element));
        }else {
          checkAgain();
        }
      }, 100);
    }    
    checkAgain();
  });
};

// example
onReadyDomElement("#header").then(function(e){
  e.html('OK');
})

The second solution:

var onReadyDomElement = function(element, callback) {
  if (jQuery(element).length) {
    callback(jQuery(element));
  } else {
    setTimeout(function() {
      onReadyDomElement(element, callback);
    }, 100);
  }
};

// example
onReadyDomElement('#header', function(e) {
  e.html('OK');
});

Javascript Code ProgrammingBoth solutions are equally effective and good, I don’t think there is a noticeable difference between them.

So any of the above javascript functions can be used to check if a given DOM element is ready (loaded/live) or wait for an element to exist on the page and is rendered to the screen.

byrev Written by:

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *