Reputation: 72
there! In my AJAX application I have a lot of content in the pages. So when the user changes the page, I have to clear the previous content in the page div. Using jQuery: cont.empty() or cont.html('') clears the DOM elements content and the associated data,events etc. But because of the big content, the performance of the page decreases dramatically. Sometimes it takes up to 500ms to clear the content on fast machine. I find out a way to clear the container super fast using pure JavaScript function:
function empty(element) {
var i;
for (i = element.childNodes.length - 1; i >= 0; i--)
element.removeChild(element.childNodes[i]);
}
This approach unfortunately generates memory leaks, because it doesn't clears the associated elements jQuery data in the cache.
Can You give me an opinion or an approach that will clear the content quick and prevents memory leaks.
As example, is there a way to clear the content fast with the native function and at some point (interval function) to loop over $.cache and remove the stored missing handlers? Something like garbage collector.
Upvotes: 4
Views: 269
Reputation: 32841
You could use a filter when you define event handlers on elements in your container. For instance, you could use:
$(document).on("click", "#item1", function() {
...
});
instead of:
$("#item1").on("click", function() {
...
});
Upvotes: 2