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
$.cachehas 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:
$("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:
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:
http://jsfiddle.net/SGZW4/2/