JavaScript事件监听器,当DOM改变时 [英] JavaScript Event Listeners for when the DOM changes

查看:160
本文介绍了JavaScript事件监听器,当DOM改变时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个Mozilla Firefox扩展(JavaScript没有必须确定它是IE还是Firefox的BS),在那里我发现自己陷入了下面的情况。在页面加载时,我添加了如下所示的事件监听器:
extension.addEventListener(DOMContentLoaded,extension.onPageLoad,true);



只要DOM被加载,就会执行monPageLoad()方法,这意味着所有的数据都被接收。这个工作,但我需要找到一种方法来添加一个侦听器,当DOM 改变。扩展应该读取appbrowser-window中的所有数据,即使是通过AJAX调用(即:twitter,facebook)进行更新。



我已经看过 DOMSubtreeModified 事件,但在最初的 DOMContentLoaded 事件触发后动态添加内容时,这似乎不起作用。



有没有人曾经克服过这个问题?



我的选择(上帝原谅我)是保持发射相同的功能与超时(2秒),重读DOM和解析它,但我更喜欢只有这样做,如果它真的改变。

解决方案

DOMSubtreeModified 确实有效,并且已经得到相当好的支持(Firefox和WebKit已经支持它多年,IE只在版本9中,Opera显然还没有)。对 DOMContentLoaded 是否被解雇没有限制,所以我建议你的测试是有缺陷的。在这里看一个例子: http://jsfiddle.net/timdown/GB6Rz/



其他DOM变异事件,如 DOMNodeInserted 更好的支持(虽然仍然不在IE< 9中),所以我建议尽可能使用那些。


I'm writing a Mozilla Firefox Extension (Javascript without the BS of having to identify if it's IE or Firefox), where I find myself stuck in the following situation. On a page load, I add event listeners like so: extension.addEventListener("DOMContentLoaded", extension.onPageLoad, true);

That would execute m "onPageLoad()" method as soon as the DOM is loaded, meaning all data is received. And that works, but I need to find a way to add a listener for when the DOM changes. The extension should read all data in the appbrowser-window, even if that's update via AJAX calls (ie: twitter, facebook).

I've looked into the DOMSubtreeModified event, but that doesn't seem to work when content is dynamically added after the initial DOMContentLoaded event has fired.

Has anyone ever overcome this problem?

My alternative (God forgive me) is to keep firing the same function with a timeout() of say 2 seconds, to reread the DOM and parse it, but I prefer to only do that if it actually changed.

解决方案

DOMSubtreeModified does work and has become reasonably well supported (Firefox and WebKit have supported it for years, IE only in version 9, Opera apparently still not at all). There is no limitation relating to whether DOMContentLoaded has fired or not, so I'd suggest your test was flawed. See here for an example: http://jsfiddle.net/timdown/GB6Rz/

Other DOM mutation events such as DOMNodeInserted are better supported (although still not in IE < 9), so I'd suggest using those where possible.

这篇关于JavaScript事件监听器,当DOM改变时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆