DOMContentLoaded已经要被放弃使用了,所以官方推荐使用MutationObserver来监听页面发生变化。但是如果你想继续使用也是可以的;Document: DOMContentLoaded event - Web APIs | MDN

MutationObserver官方文档:MutationObserver - Web APIs | MDN

all_async_search_8c3cd47.js:1125 [Deprecation] Listener added for a synchronous 'DOMNodeInserted' 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. 

all_async_search_8c3cd47.js:1125[不推荐]为同步“DOMNodeInserted”DOM突变事件添加了侦听器。不赞成使用此事件类型(https://w3c.github.io/uievents/#legacy-事件类型),并且正在将其从该浏览器中删除。使用此事件侦听器将导致当前的性能问题,并代表将来不兼容的风险。请考虑改用MutationObserver。

官方使用方式示例

监听页面元素发生变化和样式变化:变化的回调里面第一个参数是变化的元素数组,具体属性可以看官方文档:https://developer.mozilla.org/en-US/docs/Web/API/MutationRecord

//选择一个需要观察的节点
var targetNode = document.getElementById('some-id');

// 设置observer的配置选项
var config = { attributes: true, childList: true, subtree: true };

// 当节点发生变化时的需要执行的函数
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        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示例与回调函数相关联
var observer = new MutationObserver(callback);

//使用配置文件对目标节点进行观测
observer.observe(targetNode, config);

// 停止观测
observer.disconnect();

使用方式详解:

<!DOCTYPE html>

<div id="opop">
    <div class="op"></div>
    <div class="op"></div>
    <div class="op op-node-change"></div>
</div>
<!--引用jqery-->
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script>

    var targetNode =document.getElementById('opop');

    var observer = new MutationObserver(function(mutations) {
        var $node = $('#opop .op:not(.op-node-change)');
        $node.addClass('op-node-change test');
        console.log(111111);
    });

    observer.observe(targetNode, { attributes: true, childList: true, subtree: true });

</script>

上述代码是一个简单的应用示例, 是在id="opop"下,给所有的没有"op-node-change"的div 增加类"op-node-change test"
这段代码直接运行后的显示

可以看到div 的类名并没有发生改变。此时,在Console中动态的增加新的节点

然后可以看到div 的类名发生了我们所期待的变化。

这是因为MutationObserver是监听DOM树变化的接口,一开始的时候后div先加载,然后是js加载,此时DOM树没有发生变化,所有MutationObserver的回调函数没有执行,当我们动态的改变DOM树的结构时,MutationObserver监听到了变化,所以回调函数起了作用。这就是我们最后看到的结果。

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐