How to wait until an element exists?

后端 未结 19 2209
广开言路
广开言路 2020-11-22 09:14

I\'m working on an Extension in Chrome, and I\'m wondering: what\'s the best way to find out when an element comes into existence? Using plain javascript, with an interval t

19条回答
  •  无人共我
    2020-11-22 09:29

    Here is a core JavaScript function to wait for the display of an element (well, its insertion into the DOM to be more accurate).

    // Call the below function
    waitForElementToDisplay("#div1",function(){alert("Hi");},1000,9000);
    
    function waitForElementToDisplay(selector, callback, checkFrequencyInMs, timeoutInMs) {
      var startTimeInMs = Date.now();
      (function loopSearch() {
        if (document.querySelector(selector) != null) {
          callback();
          return;
        }
        else {
          setTimeout(function () {
            if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs)
              return;
            loopSearch();
          }, checkFrequencyInMs);
        }
      })();
    }
    

    This call will look for the HTML tag whose id="div1" every 1000 milliseconds. If the element is found, it will display an alert message Hi. If no element is found after 9000 milliseconds, this function stops its execution.

    Parameters:

    1. selector: String : This function looks for the element ${selector}.
    2. callback: Function : This is a function that will be called if the element is found.
    3. checkFrequencyInMs: Number : This function checks whether this element exists every ${checkFrequencyInMs} milliseconds.
    4. timeoutInMs : Number : Optional. This function stops looking for the element after ${timeoutInMs} milliseconds.

    NB : Selectors are explained at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

提交回复
热议问题