问题
在我例行维护网站前端的时候,进行评论系统的维护更新时,发现Edge浏览器的控制台当中提示下面的警告消息:
Listener added for a synchronous 'DOMNodeInsertedIntoDocument' DOM Mutation Event. This event type is deprecated (https://w3c.github.io/uievents/#legacy-event-types) and work is underway to remove it from this browser. Usage of this event listener will cause performance issues today, and represents a risk of future incompatibility. Consider using MutationObserver instead.
警告信息表明网页在使用一个已经废弃的 DOM 事件监听器 DOMNodeInsertedIntoDocument。
DOMNodeInsertedIntoDocument是一个同步的监听器,用于检测 DOM 节点插入到文档时触发的事件。这种监听方式已经被认为是不推荐使用的,并且可能会在未来被移除,因为它可能会导致性能问题。
解决方案
使用 MutationObserver,这种更现代、更高效的方式来观察 DOM 变化。了解更多,可以阅读https://cloud.tencent.com/developer/article/1417900 这篇文章。
// 创建一个观察者实例
const observer = new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.type === 'childList') {
// 当 DOM 子节点发生变更时执行的操作
// mutation.addedNodes 是一个数组,包含新增的节点
mutation.addedNodes.forEach(node => {
// 这里可以处理新增的节点
console.log('New node added:', node);
// 示例操作:为新增节点添加点击事件
if (node.nodeType === Node.ELEMENT_NODE) {
node.addEventListener('click', function() {
console.log('Node clicked:', node);
});
}
});
}
}
});
// 配置观察选项
const config = { attributes: false, childList: true, subtree: true };
// 开始观察目标节点的变化
observer.observe(document.body, config);
// 当不再需要观察时,记得断开连接
// observer.disconnect();
评论区
有 2 条评论
Yakito
越南 2025 April 20thGood theme
GarfieldTom
未知位置 2025 May 17th @YakitoTHANK YOU!