DOM 中的跟踪更改触发缓慢

Tracking changes in DOM is slow to get triggered

我为 twitch 聊天做了一段非常简单的代码,它允许我直接在聊天中看到某人发布的图像。我没有做极端验证我只是想将任何图像 link 转换为 <img> 标签。

(function() {
'use strict';
$('.tw-flex-grow-1').on("DOMSubtreeModified",function(){
    $(".link-fragment").each(function(){
        if (($(this).text().indexOf(".jpg") > 0 ) || (($(this).text().indexOf(".png") > 0 )) || (($(this).text().indexOf(".gif") > 0 ))|| (($(this).text().indexOf(".jpeg") > 0 ))){
            $(this).html("<img src='" + $(this).text() + "' width='200px'/>");
        }
    });
});

})();

我发现 DomSubTreemodified 可以跟踪 div 中的变化。但我的问题是这东西很慢。它会完成它的工作,但它真的很慢,我不知道为什么。而且我知道由于“.Each”,很多消息可能会很慢,但我稍后会解决这个问题,只有一条消息很慢。

这是错误的做法吗?如何更快地获得 domsubtreemodified 触发器?

编辑

按照评论中的建议:

(function() {
'use strict';
var targetNode = document.getElementsByClassName('tw-flex-grow-1')[0];

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        alert("test");
        if (mutation.type == 'childList') {
            $(".link-fragment").each(function(){
                if (($(this).text().indexOf(".jpg") > 0 ) || (($(this).text().indexOf(".png") > 0 )) || (($(this).text().indexOf(".gif") > 0 ))|| (($(this).text().indexOf(".jpeg") > 0 ))){
                    $(this).html("<img src='" + $(this).text() + "' width='200px'/>");
                }
            });
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

})();

最大的问题可能是对于每个突变,您都会经历每个 .link-fragment,即使您已经处理过它。您要做的只是查看新添加的节点(及其子节点)的内容和 运行 您的代码。试试这个:

// Select the node that will be observed for mutations
var targetNode = document.getElementById('target');

// Options for the observer (which mutations to observe)
var config = { attributes: false, childList: true, subtree: true };

function alterNode(node) {
    if (node.textContent.indexOf('gif') !== -1) {
        const image = document.createElement('img');
        image.setAttribute('src', node.textContent);
        image.setAttribute('width', 200);
        image.setAttribute('height', 200);
        node.appendChild(image);
    }
}
// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
    for(var mutation of mutationsList) {
        mutation.addedNodes.forEach(function(node) {
            if (node.classList.contains('link-fragment')) {
                alterNode(node);               
            }
            node.querySelectorAll('.link-fragment').forEach(function(node) {
                alterNode(node);
            })
        });
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

document.getElementById('adder').addEventListener('click', function() {
     let imageLink = document.createElement('div');
     imageLink.classList.add('link-fragment');
     imageLink.textContent = 'https://media.giphy.com/media/l2R0aKwejYr8ycKAg/giphy.gif';
     document.getElementById('target').appendChild(imageLink);
});
<div id="target"></div>

<button id="adder">Add Image Link</button>