本文介绍了DOMNodeInserted不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题..

DOMNodeInserted无法正常工作。
我不知道我是否正确使用它。

The "DOMNodeInserted" is not working as it supposed to.I am not sure if I am using it properly.

任何想法?

推荐答案

在页面加载时构建DOM时,不需要$ code> DOMNodeInserted 事件被触发。我不认为有一种方式可以在呈现HTML之前通过过滤器(或者如果我不知道)。

When constructing the DOM at page-loading, no c $ c> DOMContentLoaded 可能足够快,让用户不要注意到差异(或至少不要打扰太多)。

Filtering on DOMContentLoaded instead, might be quick enough for the user not to notice the difference (or at least not to bother too much).

当然,您必须收听DOM中的动态变化(例如,通过AJAX等加载的内容),并过滤它的动态。 A ,这更快。使用这种方法,更改应该是虚拟的透明给用户。

(这仍然需要twicking,例如处理动态节点更新。)


UPDATE

Here is a different approach using a MutationObserver, which is even more quick. Using this approach the changes should be virtualy "transparent" to the user.
(This still needs twicking, e.g. to handle dynamic node updates.)

content.js

// Highligth the element by giving it a yellow background
var doFilter = function(link) {
    link.style.backgroundColor = "yellow";
}

// Create a MutationObserver to handle events (i.e. filtering <a> elements)
var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.addedNodes) {
            for (var i = 0; i < mutation.addedNodes.length; i++) {
                var node = mutation.addedNodes[i];
                if (node.nodeName == "A") {
                    doFilter(node);
                }
            }
        }
    });
});

// Start observing "childList" events in document and its descendants
observer.observe(document, {
    childList:     true,
    subtree:       true
});

如果您决定去 方法,有这个JS库这应该使您的生活更轻松:

If you decide to go for the MutationObserver approach, there is this JS library that is supposed to make your life easier: mutation-summary

这篇关于DOMNodeInserted不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 09:23
查看更多