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.
“MutationObserver” is a Web API provided by modern browsers for detecting changes in the DOM. By using this API you can listen to changes in DOM, like added or removed nodes, attribute changes or changes in the text content of text nodes and make changes. Web apps are getting complex on the client-side nowadays.
When you update the DOM, the reflow and repaint happen. Every time the DOM changes, the browser needs to recalculate the CSS, do a layout and repaint the web page. React doesn't really do anything new. It's just a strategic move.
If multiple identical EventListeners are registered on the same EventTarget with the same parameters the duplicate instances are discarded. They do not cause the EventListener to be called twice and since they are discarded they do not need to be removed with the removeEventListener method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With