JavaScript Event Listeners for when the DOM changes [duplicate]

老子叫甜甜 提交于 2019-12-21 12:57:31

问题


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 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.


回答1:


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.




回答2:


It sounds like you're looking for DOM Mutation Events. While DOMSubtreeModified is listed on WikiPedia page, I don't see it on MDC page. The best bet is to listen to the three MDC events and see if they do what you need.




回答3:


For anyone finding this in 2017 or later, these DOM modification events have been deprecated. What you want instead is MutationObserver.

See the MutationObserver docs on MDN, or this SO answer for more details.



来源:https://stackoverflow.com/questions/5305457/javascript-event-listeners-for-when-the-dom-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!