Leaving a handler on img.onload is a memory leak?

Is it correct that this code causes a memory leak in the browser?

/**
 * @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;
};

I understand that since img is a DOM element, and because I attach JavaScript to it with the help img.onload, the browser will never garbage collect this. To fix this, I need to clean img.onload, as in

/**
 * @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;
};
+4
source share
1 answer

This should not be a leak if it is correctly implemented by the browser.

Internet Explorer (7 earler) GC, JS DOM. - , DOM, jQuery . (NB: , , - GC, IE .)

, GC , onload .

275 , , , , Chrome . ( , , 275 .) Firefox [?], , , Chrome.

?

  • javascript onload loadImageDrawIntoCanvas , img.
  • - img, img.src=, onload. Chrome (1, 2).
+1

All Articles