Example Of A Memory Leak

Here's a code sample to consider, it is contrived but bear with me:

function someFn(){

var $input = $("<input type='button' />");

$input.appendTo("body");

window.addEventListener('click', function(){

if($input.val() == ""){
// some code goes here
}

}, false);
}

 

If you were to remove $input from the DOM, it would not get garbage collected because the callback for the listener has a handle on it.

 

Likewise, be careful if you do something like this:

function someFn(){

var $someDiv = $("#someDiv");

window.addEventListener('click', function(){

if($someDiv.is(':hidden')){
// some code goes here
}

}, false);
}

 

In this case, if you ever removed $someDiv from the DOM, it would not be garbage collected. So this may be a better solution:

function someFn(){

var $someDiv = $("#someDiv");

window.addEventListener('click', function(){

if($("#someDiv").is(':hidden')){
// some code goes here
}

}, false);
}

 

In the past I would have taken the previous route because I always tried to reduce the amount of times I wrapped something in jQuery, but now I'll have to be careful about what my code is doing. If I never intend to remove $someDiv, then maybe the previous sample is OK, but if there is a possibility that I remove it, then the last sample will avoid a memory leak.

Add a Comment...

 

Comments

Hi there, I read your blogs like every week. Your story-telling style is awesome, keep it up! maglia real madrid 2017 - 5/16/2017

BeatrizBr Elfenbenskusten DustyPcqi Angelicap Barcelona ChristieM GlendaHar Slovakien SophiaBur MarlaPann Roma TraceerpK KerriSchu Tyskland Milagrosy - 3/08/2017

EmelyTufn Rumanien KlaraMose CharissaW Elfenbenskusten MorganAli NataliaLe Argentina CassieFre TCCRaleig Spanien RonSmpps AthenaChe Italien JacobHind NganBrack Atletico Madrid ClairSepp KeiraFair Dortmund NicolasSe Dickqkayz Olympique De Marseille OmaynBekk LolaChinn Inter Milan KimberlyM QuyenFjuh Seattle Sounders ElijahTor - 3/07/2017