4
这段代码在浏览器中导致内存泄漏是否正确?在img.onload上留下处理程序是内存泄漏?
/**
* @param {Canvas2DRenderingContext} ctx
* @param {string} url
*/
function loadImageDrawIntoCanvas(ctx, x, y, url) {
var img = new Image();
img.onload = function() {
ctx.drawImage(img, x, y);
}
img.src = url;
};
我的理解是,因为IMG是一个DOM元素,因为我安装的JavaScript将其与img.onload
浏览器将不会垃圾回收这一点。为了纠正我需要清除img.onload
在
/**
* @param {Canvas2DRenderingContext} ctx
* @param {string} url
*/
function loadImageDrawIntoCanvas(ctx, x, y, url) {
var img = new Image();
img.onload = function() {
ctx.drawImage(img, x, y);
img.onload = null; // detach the javascript from the Image
img = null; // needed also so the closure doesn't keep
// a reference to the Image?
}
img.src = url;
};