Reputation: 1295
I know this could be handled in some way, but as of now, this is giving me a real hard time. I am writing a script and want to fire some particular functions when a DOM manipulation is complete. I cannot modify/add/remove any other script (as it might be injected into the page using some framework). The page is using ajax requests(not implemented in jQuery) to load/modify content. Now I want an event to be triggered when every DOM modification has been completed. My current approach is to fire the function at every DOMSubtreeModified event. Something like this
$(document).bind('DOMSubtreeModified', doSomeStuff);
But the drawback of this approach is, let say the ajax loads 10 elements in a call, then for each element doSomeStuff is fired. Can this be limited to only firing after the 10th element is loaded? Something like resetting the $(document).ready() event? so $(document).ready() is fired every time the DOM is ready (after loading ajax content)
Upvotes: 7
Views: 6750
Reputation: 2052
I know I'm a bit late to the party, but it sounds like you may want to debounce your doSomeStuff
function. If you're not opposed to introducing a dependency upon Underscore.js, it has a nice debounce function.
Upvotes: 0
Reputation: 5055
With the Mutation Observer you can listen on changes and if the event is fired the document was changed.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// Add the actions to be done here if a changes on DOM happened
console.log(mutations, observer);
});
// Register the element root you want to look for changes
observer.observe(document, {
subtree: true,
attributes: true
});
Upvotes: 2
Reputation: 8706
In jQuery, there is a method ajaxComplete
, which calls a given function after every finished AJAX call. See more here.
I'd suggest to use jQuery or (in case this is not an option) analyze source code of this function to see how it's done there.
Upvotes: 1