I built my first long running AJAX heavy app and memory leaks are eating me alive. I don't want to post too much code because it should be my job to fix it all, but I need some help.
Does this code leak? Where? Why? and if you'd be so kind as to suggest a fix.
function list_stuff(data, type, where, order) { var items = []; $.each(data, function (i, item) { items.push( //using jquery $data might make this look more readable '<li data-lat="' + item.lat + '" data-lng="' + item.lng + '" data-type="' + type + '" data-id="' + item.group_id + '" data-privacy="' + item.privacy + '" type = "li"> ' + '<div class ="li_title">' + item.name + '</div>' + '<div class ="li_description">' + item.description + '</div>' + '<div class ="li_footer">' + 'Miles: ' + item.distance + ' People: ' + item.people); if (item.privacy != 0) { items.push(' (Private group) '); } if (where == '#thelist') { items.push('</div>' + '<button data-action ="2" type ="button" class ="join_button" onclick="join_group(this)">Join</div></li>'); } else if (where == '#thelist2') { items.push('</div>' + '<button data-action= "4" type ="button" class ="join_button" onclick="join_group(this)">Leave</div></li>'); } }); if (order === 'append') { $(where).append(items.join('')); } else { $(where).prepend(items.join('')); } scroll.refresh(); } My AJAX looks like this:
function ajax(send,where) { $.ajax({ url: where, type: 'POST', dataType: 'json', data: send, success: function(a) { if (a.success===1) { list_stuff(a.data, a.type, '#list1','append'); } else { create_group_problem(a.msg); } if(a.msg.length >1 ) { msg_disp(a.msg); } }, error: function(err){ msg_disp('error'); } }); } I understand (tenuously) that JavaScript gets garbage collected, but doesn't this form a circular reference that may prevent it from being collected? Please correct me if I'm wrong, but here is my reasoning:
list_stuff():'<button data-action ="2" type ="button" class ="join_button" onclick="join_group(this)">Join</div></li>'JS -> DOM
Generated LI Element:
onclick="join_group(this)"DOM ->JS
Last question for the sake of learning/understanding: if this is not a circular reference, that will be prevented from being garbage collected, how can I change it to become one?
function join_group(block) { var $block = $(block); var pass = 0; var c_id = $block.closest("li").data("id"); var p = $block.closest("li").data("privacy"); var action = $block.data("action"); if(p !== 0 && action ==3){ pass = prompt("This group requires a password to join."); if (pass === null || pass ==='') { return; } } var send ={ group_id: c_id, group_action: action, privacy:p, password: pass, }; ajax(send, 'group'); }