使突变观察者更快,资源更少

Make mutation observer faster and less resource heavy?

本文关键字:资源 观察者 突变      更新时间:2023-09-26

我试图使用一个突变观察者,但我发现这是很难实现没有浏览器变慢。也许这只是我的执行,但我希望有人看看,看看是否有什么可以改进。

我也试图检查突变的p标签,但我似乎不能弄清楚。现在我在检查document.body的突变因为我不知道如何实现p

var arrayOfP = $("p").text(); //Get p tags
var observer = new WebKitMutationObserver(function(mutations) {
    tempArrayOfP = $("p").text(); //Get p after mutation
    tempArrayOfP = tempArrayOfP.replace(arrayOfP,''); //Get the difference between before and after mutation (this line doesn't seem to work...
    arrayOfP = $("p").text(); //Store new case of current p tags
    chrome.runtime.sendMessage(tempArrayOfP, manageResponse); //Send p tags to other file in chrome extension
});
observer.observe(document.body, { attributes: true, childList: true, characterData: true });

任何想法?tempArrayOfP替换似乎不起作用,目前我的chrome扩展是在发送消息时重新做页面上的一切。

谢谢你的帮助。谢谢。

传递给回调的突变可以提供旧值和新值,这将使您不必为每个突变遍历DOM。

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    var oldValue, newValue;
    if(mutation.type === 'characterData' &&
        mutation.target.parentNode && 
        mutation.target.parentNode.nodeName.toLowerCase() === 'p')
    {
      oldValue = mutation.oldValue;
      newValue = mutation.target.textContent;
    } else if(mutation.target.nodeName.toLowerCase() === 'p' && 
             mutation.addedNodes.length &&
             mutation.removedNodes.length) 
    {
      oldValue = mutation.removedNodes[0].textContent;
      newValue = mutation.addedNodes[0].textContent;
    } else {
      return;
    }
                                        
    // do stuff
    document.write('old: ' + oldValue + ', new: ' + newValue);
  }); 
}); 
  
  observer.observe(document.body, { characterDataOldValue: true, subtree: true, childList: true, characterData: true });
// test
document.querySelector('p').textContent = 'good bye';
<p>hello world</p>

至于提取新旧文本之间的差异,您的方法假设突变没有删除任何文本,或者在现有文本之间插入文本。如果发生这种情况,replace中的字符串将不匹配任何内容。

var elems = [].slice.call(document.getElementsByTagName("p"));
var text = elems.map(function(el) {
  return el.textContent
})
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.target.nodeName === "P") {
      var index = elems.indexOf(mutation.target);
      console.log("mutation type:", mutation.type + "'n"
                 , "new text:", mutation.addedNodes[0].nodeValue + "'n"
                 , "old text:", text[index]);
    }
  });
})
observer.observe(document.body, {
  childList: true,
  characterData: true,
  subtree: true
});
document.getElementsByTagName("p")[0].textContent = 123;
document.getElementsByTagName("p")[1].textContent = 456;
<p>abc</p>
<p>def</p>