【发布时间】:2018-12-12 19:37:14
【问题描述】:
我有一段非常简单的代码,用于 twitch 聊天,它允许我直接在聊天中看到某人发布的图像。我没有进行极端验证,我只是想将任何图像链接转换为<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 触发器?
编辑
遵循 cmets 中的建议:
(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);
})();
【问题讨论】:
-
@SLaks 你能检查一下修改后的代码吗?有时会触发测试,但不会触发子列表
-
它实际上只在此代码开头触发
标签: javascript jquery html google-chrome userscripts