I have a plugin with the following structure:
(function($) {
$.fn.drawFieldsTable = function(options) {
var settings = {
url : 'ajax/pathToFile.php'
};
if (options) {
settings = $.extend(settings, options);
}
return this.each(function() {
$this = $(this);
$.ajax({
url : settings.url,
type : 'GET',
data: // some request data here
success: function(result) {
drawFieldElements(result, $this);
}
});
function drawFieldElements(fields, container)
{
var replacement = container.clone()
.empty();
$.each(fields, function(i) {
var field;
field = buildFieldItem(i, this);
replacement.append(field);
});
container.replaceWith(replacement);
}
function buildFieldItem(i, fieldDataObj)
{
var $field = $('<div></div>')
.addClass('field')
.attr('data-fieldname', i)
.attr('data-ord', fieldDataObj.ord);
return $field;
}
});
};
})(jQuery);
I experience a major memory leak on every buildFieldItem call. If I do not call this function or make it an empty function or just do not use its parameters in its scope – there is no leak. The leak only happens in Internet Explorer (8). In other browsers it’s all ok. Requesting assistance. Thanks in advance.
UPDATE
I’ve updated my question for better demonstrating what buildFieldItem actually does.
As soon as fieldDataObj may contain about 100 items, having these 4 lines solely causes a fountain, not a leak in IE.
UPDATE 2
I’ve replaced clone() and empty() with creating a new div and I also minified buildFieldItem to look like:
function buildFieldItem(i, fieldDataObj)
{
var $field = $('<div></div>')
.addClass('field');
return $field;
}
Still leaking. The only pattern that doesn’t leak is:
function buildFieldItem(i, fieldDataObj)
{
var $field;
return $field;
}
Looks like a complete nonsense. The less code in function – the smaller is an overall leak. Could it be that IE can’t delete a reference to the whole function or smth like that?
So, I’ve finally found some time to go back to this old question and finalize. I’ve solved the problem quite quickly, but I’ve just been busy.
The following lines were causing memory leaks in IE:
As you can see, it creates some kind of circular reference when adding a handler for the change event. The reference IE is not smart enough to break.
The fact is, commenting this out was my first try, but as soon as I’ve also had draggable functionality implemented in the same file, the leak remained, as draggables were causing it too! That’s why I was struggling with that. Moving draggables outside the plugin code solved it.
Thanks everybody for posting comments and answers. I am sorry for not posting the full code, I thought I was smart enough to post only problematic lines. Sorry for late answer too.