Make function wait until element exists

前端 未结 11 1896
一向
一向 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 17:57

    Depending on which browser you need to support, there's the option of MutationObserver.

    EDIT: All major browsers support MutationObserver now.

    Something along the lines of this should do the trick:

    // callback executed when canvas was found
    function handleCanvas(canvas) { ... }
    
    // set up the mutation observer
    var observer = new MutationObserver(function (mutations, me) {
      // `mutations` is an array of mutations that occurred
      // `me` is the MutationObserver instance
      var canvas = document.getElementById('my-canvas');
      if (canvas) {
        handleCanvas(canvas);
        me.disconnect(); // stop observing
        return;
      }
    });
    
    // start observing
    observer.observe(document, {
      childList: true,
      subtree: true
    });
    

    N.B. I haven't tested this code myself, but that's the general idea.

    You can easily extend this to only search the part of the DOM that changed. For that, use the mutations argument, it's an array of MutationRecord objects.

提交回复
热议问题