Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - 如何等待直到元素存在?(How to wait until an element exists?)

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

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

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...