我想我实际上有很多内存泄漏,但影响最大的是:
- 我创建了一个 256 个 div 的网格
- 我将网格传递给一个淡出 div 的函数
- 然后我从 DOM 中删除网格
解决这个问题的最简单方法是$cells = $grid = null;
在fadeVertical完成后添加并添加$div = null;
currentImageToGrid吗?还是比这更复杂?(请参阅我正在谈论的优化的评论。)
我已经删掉了很多代码,一个完整的 JSFiddle 在这里:http: //jsfiddle.net/GBWKh/
谢谢,
乔
function demoFoStackOverflow(){
transition(750, function(){});
}
function currentImageToGrid(xCount, yCount)
{
var $container = $('<div />').addClass('grid').width($imgCurrent.width()).height($imgCurrent.height()).css({ marginLeft: (($imgCurrent.parent().width() - $imgCurrent.width()) / 2) + 'px' }).click(function () {
$imgCurrent.trigger('click');
$(this).remove();
});
var sliceWidth = Math.round($imageContainer.width() / xCount);
var sliceHeight = Math.round($imageContainer.height() / yCount);
var xMod = 0;
var yMod = 0;
for (var y = 0; y < yCount; y++) {
for (var x = 0; x < xCount; x++) {
var $div = $('<div/>');
$div.css({
height: sliceHeight + yMod,
width: sliceWidth + xMod,
left: x * sliceWidth + xMod,
top: y * sliceHeight + yMod,
backgroundImage: 'url(' + $imgCurrent.attr('src') + ')',
backgroundPosition: (0 - x * sliceWidth + xMod) + 'px ' + (0 - y * sliceHeight + yMod) + 'px'
});
$container.append($div);
// $div = null; <-- See here
}
}
$imageContainer.append($container);
return $container;
}
function transition(duration, callback) {
// The more cells we have the better it looks but it lags in ff/ie
var x = 16;
var y = 16;
var $grid = currentImageToGrid(x, y);
$imgCurrent.hide();
var transitionName;
transitionName = _args.transitions[transitionIndex % _args.transitions.length];
transitionIndex++;
runTransition(transitionName, $grid, x, y, duration, function () {
var waitForAnimationToEnd = setInterval(function () {
// Although the set interval timer used in the trasition has finished there may still be animations running
if (!$grid.children().is(':animated')) {
$grid.remove();
callback();
clearInterval(waitForAnimationToEnd);
}
}, 20);
});
}
function runTransition(name, $grid, xCount, yCount, duration, callback) {
if (name == 'fadeUp') { fadeUp($grid, xCount, yCount, duration, callback); }
// Lots of others removed for brevity
}
function fadeUp($grid, xCount, yCount, duration, callback) {
fadeVertical($grid, xCount, yCount, duration, callback, 'up');
}
function fadeVertical($grid, xCount, yCount, duration, callback, direction) {
var y = direction == 'down' ? 0 : yCount - 1;
var $cells = $grid.children();
var timer = setInterval(function () {
for (var x = 0; x < xCount; x++) {
$($cells[y * xCount + x]).fadeTo(duration / yCount, 0);
}
if (direction == 'down')
y++;
else
y--;
if (y == 0 || y == yCount) {
clearInterval(timer);
// $cells = null; <-- See here
// $grid = null; <-- See here
callback();
}
}, duration / yCount);
}