Reputation: 589
I'm working on a mobile-optimized site which features a gallery, having lots (1oo+ in some cases) of images on a page.
I figured having that many images might crash a mobile device, so I created a function that checks periodically if there are more than a given number of img elements in the page, and if so, remove some of them from the DOM with .empty().remove();
The page still does crash at certain points on a Ipod 3G (only mobile device available for testing atm) so I'm asking, if I remove the <img>
element from the dom, does that clear up memory for the browser?
Upvotes: 2
Views: 961
Reputation: 1
The safest bet here is as previously discussed the Node.removeChild method; however memory allocation is governed by the Javascript Garbage collector, and you cannot "clean" on demand.
Therefore typically your goal is achieved, but if you reach the memory limit before garbage collection has the chance to dereference the dom elements removed, then the page could potentially crash the browser.
"assuming your code has not kept any other reference to the node elsewhere, it will immediately become unusable and irretrievable, and will usually be automatically deleted from memory after a short time"
Upvotes: 0
Reputation: 1947
https://developer.mozilla.org/En/DOM/Node.removeChild
"The removed child node still exists in memory, but is no longer part of the DOM. ..."
jQuery source code:
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
Upvotes: 3