简体   繁体   中英

Does removing an element (a img) from the DOM with jquery clear the memory allocated?

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?

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;
},

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.

  • Node.removeChild

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM