Check if a given DOM element is ready

后端 未结 5 798
不知归路
不知归路 2020-12-29 04:28

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

5条回答
  •  抹茶落季
    2020-12-29 05:00

    -------- 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
    })
    

提交回复
热议问题