扩展插件中观察DOM的变化
MutationObserver是监听DOM变化与当元素变化时做适当操作的一个解决方法。在下面的例子中我们使用计时器模拟了内容的动态加载,第一个元素”target”创建后,创建”subTarget”。
在扩展中的代码,rootObserver
首先开始工作,直到targetElement
被创建后rootObserver
停止,然后elementObserver
开始工作。这个级联观测可以在发现subTargetElement
时提醒你。
这个方法在为动态加载内容的网站开发扩展插件时,是很有用的。
const observeConfig = {
attributes: true,
childList: true,
characterData: true,
subtree: true
};
function initExtension(rootElement, targetSelector, subTargetSelector) {
var rootObserver = new MutationObserver(function(mutations) {
console.log("Inside root observer");
targetElement = rootElement.querySelector(targetSelector);
if (targetElement) {
rootObserver.disconnect();
var elementObserver = new MutationObserver(function(mutations) {
console.log("Inside element observer")
subTargetElement = targetElement.querySelector(subTargetSelector);
if (subTargetElement) {
elementObserver.disconnect();
console.log("subTargetElement found!")
}
})
elementObserver.observe(targetElement, observeConfig);
}
})
rootObserver.observe(rootElement, observeConfig);
}
(function() {
initExtension(document.body, "div.target", "div.subtarget")
setTimeout(function() {
del = document.createElement("div");
del.innerHTML = "<div class='target'>target</div>"
document.body.appendChild(del)
}, 3000);
setTimeout(function() {
var el = document.body.querySelector('div.target')
if (el) {
del = document.createElement("div");
del.innerHTML = "<div class='subtarget'>subtarget</div>"
el.appendChild(del)
}
}, 5000);
})()
MEET THE NEW JSTIPS BOOK
You no longer need 10+ years of experience to get your dream job.
Use the 100 answers in this short book to boost your confidence and skills to ace the interviews at your favorite companies like Twitter, Google and Netflix.
GET THE BOOK NOW
MEET THE NEW JSTIPS BOOK
The book to ace the JavaScript Interview.
A short book with 100 answers designed to boost your knowledge and help you ace the technical interview within a few days.
GET THE BOOK NOW