使突变观察者更快,资源更少
Make mutation observer faster and less resource heavy?
我试图使用一个突变观察者,但我发现这是很难实现没有浏览器变慢。也许这只是我的执行,但我希望有人看看,看看是否有什么可以改进。
我也试图检查突变的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>
相关文章:
- 未激发路由的控制器属性上的观察者
- 将属性设置为未定义时未通知观察者
- 检测 DIV 的高度何时变化,而无需轮询或突变观察者
- JavaScript:为什么Addy's观察者模式
- 设置多个观察程序以触发动态事件的角度替代解决方案 - 优化的观察者模式
- 被动.js模式间接观察者报告相同的值
- 将$scope对象作为参数提供给$digest中的观察者背后的逻辑
- 取代了棱角分明的深度观察者
- 突变观察者尚未定义
- 突变观察者未能检测到元素's删除dom
- 手动调整元素大小;不要在Chrome中激发突变观察者
- 共同描述编译器和观察者
- 如何确保对观察者的订阅调用最初接收到最新的值
- 未捕获的类型错误:无法执行'观察'在'突变观察者':参数1不是'节点'
- 在jQuery数据表中使用AngularJS观察者的方法是什么
- nodejs:原子文件替换操作,只触发一次一些观察者
- 阵列突变而不触发特定的观察者
- 无限循环当观察父对象时,观察者不更新任何值
- 基于观察者布尔值执行 ui-sref
- 使突变观察者更快,资源更少