[英]DOMNodeInserted/Removed event polyfills (or similar events)
I need a way to listen for changes for when a node's children are removed or added. 我需要一种方法来侦听更改或删除节点的子级时的更改。 I made an autoscrolling plugin that keeps an element scrolled to the bottom as new items are added.
我制作了一个自动滚动插件,可以在添加新项目时使元素滚动到底部。 The event I'm listening to is
DOMNodeInserted
and DOMNodeRemoved
. 我正在监听的事件是
DOMNodeInserted
和DOMNodeRemoved
。
I was looking for polyfills for DOMNodeInserted
and DOMNodeRemoved
. 我一直在寻找
DOMNodeInserted
和DOMNodeRemoved
DOMNodeInserted
。 Looking around I wasn't able to find any that already existed. 环顾四周,我找不到任何已经存在的东西。 The event is not supported in all browsers and is currently deprecated .I have a simple (likely naive) polyfill I wrote quickly but I doubt it works (well).
并非所有浏览器都支持该事件, 目前不建议使用该事件。我编写了一个简单的(可能很幼稚的)polyfill,但我对此写得很快,但我怀疑它是否有效。
I know these events are deprecated , but is there a better way to listen for element children changes? 我知道这些事件已被弃用 ,但是有没有更好的方法来监听子元素的更改?
(function() {
var works = false;
var $test = document.createElement("div");
var $testchild = document.createElement("a");
$test.addEventListener("DOMNodeInserted", function() {
works = true;
}, false);
$test.appendChild($testchild);
if(!works) {
var nodeproto = Node.prototype;
var nativeAppend = nodeproto.appendChild;
var nativeRemove = nodeproto.removeChild;
nodeproto.appendChild = function() {
nativeAppend.apply(this, arguments);
this.fireEvent("DOMNodeInserted");
};
nodeproto.removeChild = function() {
nativeRemove.apply(this, arguments);
this.fireEvent("DOMNodeRemoved");
};
}
})();
I ended up writing a reasonably compliant polyfill for MutationObserver
using interval checks of a cloned childList
(similar to what @plalx mentioned in his comments) instead of falling back on the MutationEvent
s. 我最终使用对复制的
childList
间隔检查(类似于他的评论中的@plalx)为MutationObserver
编写了一个合理合规的 polyfill,而不是依赖MutationEvent
。 MutationEvent
s will be more performant for most scenarios as any poll vs interrupt implementations but compatibility sucks MutationEvent
在大多数情况下都将具有更高的性能,因为任何轮询与中断实现都可以,但是兼容性很差
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.