美文网首页
MutationObserver监听dom节点加载完成

MutationObserver监听dom节点加载完成

作者: 踏雪_739a | 来源:发表于2021-12-09 10:36 被阅读0次
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
    </body>
    <script>
       
        var listeners = [];
        var doc = document;
        var MutationObserver = MutationObserver || WebKitMutationObserver;
        var observer;
    
        function observerEleReady(selector, fn) {
            // 储存选择器和回调函数
            listeners.push({
                selector: selector,
                fn: fn
            });
            if (!observer) {
                // 监听document变化
                observer = new MutationObserver(check);
                observer.observe(doc.documentElement, {
                    childList: true,
                    subtree: true
                });
            }
            // 检查该节点是否已经在DOM中
            check();
        }
    
        function check() {
            // 检查是否匹配已储存的节点
            for (var i = 0; i < listeners.length; i++) {
                var listener = listeners[i];
                // 检查指定节点是否有匹配
                var elements = document.querySelectorAll(listener.selector);
                for (var j = 0; j < elements.length; j++) {
                    var element = elements[j];
                    // 确保回调函数只会对该元素调用一次
                    if (!element.ready) {
                        element.ready = true;
                        // 对该节点调用回调函数
                        listener.fn.call(element, element);
                    }
                }
            }
        }
    
        setTimeout(function(){
            document.body.innerHTML = "<h1>aserfdsthhhh</h1>"
        }, 1000);
        
        observerEleReady("h1", function(){
            console.log("h1加载完成")
        })
    </script>
    </html>
    

    相关文章

      网友评论

          本文标题:MutationObserver监听dom节点加载完成

          本文链接:https://www.haomeiwen.com/subject/afcffrtx.html