How to wait until an element exists?

后端 未结 19 1737
广开言路
广开言路 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:54

    DOMNodeInserted is being deprecated, along with the other DOM mutation events, because of performance issues - the recommended approach is to use a MutationObserver to watch the DOM. It's only supported in newer browsers though, so you should fall back onto DOMNodeInserted when MutationObserver isn't available.

    let observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (!mutation.addedNodes) return
    
        for (let i = 0; i < mutation.addedNodes.length; i++) {
          // do things to your newly added nodes here
          let node = mutation.addedNodes[i]
        }
      })
    })
    
    observer.observe(document.body, {
        childList: true
      , subtree: true
      , attributes: false
      , characterData: false
    })
    
    // stop watching using:
    observer.disconnect()
    
    0 讨论(0)
提交回复
热议问题