Make function wait until element exists

前端 未结 11 1920
一向
一向 2020-11-28 17:40

I\'m trying to add a canvas over another canvas – how can I make this function wait to start until the first canvas is created?

function PaintObject(brush) {         


        
11条回答
  •  生来不讨喜
    2020-11-28 18:01

    Here's a minor improvement over Jamie Hutber's answer

    const checkElement = async selector => {
      while ( document.querySelector(selector) === null) {
        await new Promise( resolve =>  requestAnimationFrame(resolve) )
      }
      return document.querySelector(selector); 
    };
    

    To use:

    checkElement('.myElement').then((selector) => {
      console.log(selector);
    });
    

提交回复
热议问题