javascript - 让突变观察者更快、更少占用资源?

标签 javascript jquery google-chrome-extension google-chrome-app mutation-observers

我正在尝试使用突变观察器,但我发现在不降低浏览器速度的情况下很难实现。也许这只是我的实现,但我希望有人看一下,看看是否有任何可以改进的地方。

我还尝试检查 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 中的字符串将不会匹配任何内容。

关于javascript - 让突变观察者更快、更少占用资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32425192/

相关文章:

javascript - 谷歌浏览器中的图像宽度问题

javascript - 运行 tabs.executeScript 时未选中 runtime.lastError?

javascript - chrome.identity.getAuthToken 返回 "bad client id: {0}"错误

javascript - 通过 Chrome 扩展在 Facebook 上分享

jquery 移动样式不起作用

javascript - 为什么我不能为我的数组设置一个 css 属性。 Hangman Javascript 编码

javascript - 为什么 document.getElementById 返回的对象与 $ (".class").last().get() 不同?

javascript - 使用 .prop() 创建全选复选框,但不希望删除该复选框

javascript - 我可以使用 jQuery 为代码中的所有链接编写 e.preventDefault() 吗?

javascript - 需要 Jquery 幻灯片中的图像作为链接