Skip to content

Commit

Permalink
Avoid using jQuery's clone() method
Browse files Browse the repository at this point in the history
Avoiding the use of jQuery's clone() and empty() methods helps to decrease the
amount of memory used by the project. The less garbage present on the the
heap, the fewer garbage collection pauses the application will enounter, which
will help make scrolling smoother and the application more responsive.
  • Loading branch information
mattbasta authored and Matt Basta committed Apr 11, 2014
1 parent fbbadad commit 38fb9a2
Showing 1 changed file with 30 additions and 4 deletions.
34 changes: 30 additions & 4 deletions jquery.stalker.js
Expand Up @@ -99,7 +99,7 @@

// We use jElement.height() instead of outerHeight() since original
// padding is still applied to placeholder element
this.placeholder = this.jElement.clone(false).empty().css('height', this.jElement.height());
this.placeholder = this.styleClone(this.jElement).css('height', this.jElement.height());

this.stalking = false;

Expand Down Expand Up @@ -192,7 +192,7 @@
// element's original styles intact for when we're done stalking
// We want to do this as late as possible.
// We won't need the descendents, so don't bother with them
me._jElementClone = me.jElement.clone(true, false);
me._jElementClone = me.styleClone(me.jElement);

setPosition('top');

Expand All @@ -217,7 +217,7 @@
// element's original styles intact for when we're done stalking
// We want to do this as late as possible.
// We won't need the descendents, so don't bother with them
me._jElementClone = me.jElement.clone(true, false);
me._jElementClone = me.styleClone(me.jElement);

setPosition('bottom');

Expand Down Expand Up @@ -250,7 +250,7 @@
}

me._baseOffset = me.placeholder.offset();
me.jElement.width(me._baseWidth).css('left', me._baseOffset.left+'px');
me.jElement.width(me._baseWidth).css('left', me._baseOffset.left + 'px');
}
else
{
Expand All @@ -266,6 +266,32 @@
stalk();
};

Stalker.prototype.styleClone = function($node)
{
// Extract the node from the jQuery object for cloning.
var node = 'nodeName' in $node ? $node : $node[0];
var clone = document.createElement(node.nodeName);

var i, length, attr;
for (i = 0, length = node.attributes.length; i < length; i++)
{
attr = node.attributes[i];
clone.setAttribute(attr.name || attr.nodeName, attr.value || attr.nodeValue);
}

// Clean and re-merge attributes.
if (clone.clearAttributes)
{
clone.clearAttributes();
}
if (clone.mergeAttributes)
{
clone.mergeAttributes(node);
}

return $(clone);
};

// A really lightweight plugin wrapper around the constructor,
// preventing against multiple instantiations
$.fn[pluginName] = function ( options )
Expand Down

0 comments on commit 38fb9a2

Please sign in to comment.