这段代码在浏览器中会导致内存泄漏,这个说法正确吗?
/**
* @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;
};
我的理解是因为是一个DOM元素,并且我使用
img.onload
将JavaScript附加到它上面,所以浏览器永远不会对其进行垃圾回收。要纠正这个问题,我需要清除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;
};