Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

(我正在开发Chrome中的扩展程序,我想知道:找出元素何时存在的最佳方法是什么?)

Using plain javascript, with an interval that checks until an element exists, or does jQuery have some easy way to do this?

(使用纯JavaScript,间隔检查直到元素存在,或者jQuery是否有一些简单的方法来执行此操作?)

  ask by mattsven translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
344 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

(由于性能问题,不建议使用DOMNodeInserted以及其他DOM突变事件-推荐的方法是使用MutationObserver来监视DOM。)

It's only supported in newer browsers though, so you should fall back onto DOMNodeInserted when MutationObserver isn't available.

(不过,只有新的浏览器才支持它,因此,当MutationObserver不可用时,您应该使用DOMNodeInserted 。)

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (!mutation.addedNodes) return

    for (var i = 0; i < mutation.addedNodes.length; i++) {
      // do things to your newly added nodes here
      var node = mutation.addedNodes[i]
    }
  })
})

observer.observe(document.body, {
    childList: true
  , subtree: true
  , attributes: false
  , characterData: false
})

// stop watching using:
observer.disconnect()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...