用于现代JavaScript的Observer API
作者 | Cody Bennett
MutationObserver
// 选择要观察突变的节点
const targetNode = document.getElementById('element');
// 观察者的选项(观察哪些突变)
const config = {
attributes: true,
childList: true,
subtree: true,
};
// 创建一个观察者实例,链接到一个回调,以便在观察到突变时执行。
const observer = new MutationObserver((mutations, observer) => {
mutations.forEach(mutation => {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
} else if (mutation.type === 'attributes') {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
});
});
// 开始观察目标节点的配置突变情况
observer.observe(targetNode, config);
// 之后,你可以停止观察
observer.disconnect();
IntersectionObserver
// 选择要观察突变的节点
const targetNode = document.getElementById('element');
// 观察者的选项(观察哪些突变)
const config = {
rootMargin: '-100% 0px 0px 0px',
};
// 创建一个观察者实例,链接到一个回调,以便在观察到突变时执行。
const intersectionObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('Observing.');
// 之后,你可以停止观察
observer.unobserve(entry.target);
}
});
});
// 开始观察
intersectionObserver.observe(targetNode, config);
ResizeObserver
// 选择要观察突变的节点
const targetNode = document.getElementById('element');
const resizeObserver = new ResizeObserver((entries, observer) => {
entries.forEach(entry => {
console.log(`Element size: ${entry.width}px x ${entry.height}px`);
console.log(`Element padding: ${entry.top}px ; ${entry.left}px`);
// 之后,你可以停止观察
observer.unobserve(entry.target);
});
});
// 开始观察
resizeObserver.observe(targetNode);
PerformanceObserver
// 观察者的选项(观察哪些突变)
const config = {
entryTypes: ['resource', 'mark', 'measure']
};
const observer = new PerformanceObserver(list => {
list.getEntries().forEach(entry => {
// 在控制台上显示每个报告的测量
console.log(
`Name: ${entry.name}`,
`Type: ${entry.entryType}`,
`Start: ${entry.startTime}`,
`Duration: ${entry.duration}`,
);
});
});
// 开始观察
observer.observe(config);
performance.mark('registered-observer');
评论