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.
$.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.
$("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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With