Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is $.cache deemed too large?

I recently read in this tutorial that certain jQuery leaks are trackable through the $.cache variable, and you should always check its size, if it's too large, you're doing something wrong.

Well, how large is too large? Is there a way to inspect a variable to see how much memory it is eating up?

I'm working on a website that caches 210 objects only by loading the homepage. Is that too much? I would appreciate a thorough explanation about the issue here.

like image 647
ChuckE Avatar asked Oct 22 '22 07:10

ChuckE


1 Answers

$.cache's size at face value does not tell anything about memory leaks. It could be very small and still have a memory leak, or it could be very large and not have any memory leak.

If you know you have 10 event listeners bound with jQuery on the page at a time, and yet $.cache has entries for more, then you know you are leaking.

A huge memory saver is to use event delegation rather than attaching event listeners to each individual element.

Say:

<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>

$("li").on( "click", fn ) would attach 3 individual event handlers (more, if you have more li's of course), whereas $("ul").on( "click", "li", fn) would attach just one regardless of how many li-elements you have and yet have the same result.


Example of leak:
$("button").click( function() {
    $("#target")[0].innerHTML = "";
    $("<div>").appendTo( $("#target")).click( $.noop );
    $("#log").text( Object.keys( $.cache ).length );
});​

http://jsfiddle.net/SGZW4/1/

Reason being that .innerHTML is used, which is not part of jQuery so it cannot do clean up.

Fix is to use jQuery method for the same:

$("button").click( function() {
    $("#target").html("");
    $("<div>").appendTo( $("#target")).click( $.noop );
    $("#log").text( Object.keys( $.cache ).length );
});​

http://jsfiddle.net/SGZW4/2/

like image 73
Esailija Avatar answered Nov 15 '22 05:11

Esailija