Javascript + IMG tags = memory leak. Is there a better way to do this?

By : Dustin
Source: Stackoverflow.com
Question!

I've got a web page that's using jquery to receive some product information as people are looking at things and then displays the last product images that were seen. This is in a jquery AJAX callback that looks pretty much like this:

if(number_of_things_seen > 10) {
  $('#shots li:last-child').remove();
}

$('<li><img src="' + p.ProductImageSmall + '"></li>').prependTo('#shots');

However, it seems to leak quite a bit of memory. Visually, it does the right thing, but the footprint grows indefinitely.

Safari's DOM inspector shows the DOM is how I would expect it to be, but it seems to maintain references to every image that it has displayed (as seen in this screenshot in case anyone is interested).

I've added

$('#shots li:last-child img').remove();

to the removal statement to no noticable effect.

Is there some magic necessary to let the browser release some of this stuff?

By : Dustin


Answers

As I have recently discovered, there is a bug in Firefox that causes orphaned IMG tags to leak.

This can be worked around by moving the images to CSS:

if(number_of_things_seen > 10) {
  $('#shots li:last-child').remove();
}

$('<li><div style="background-image: url(\'' + p.ProductImageSmall +
     '\'); background-repeat: no-repeat; background-position: center; '+
     ' width: 20px; height: 20px"></div></li>').prependTo('#shots');

Check to see if this solves your memory leak.

By : Willem M.


Browsers are notorious for memory leaks. It sounds like the problem occurs when the page is left running for a long time. How about refreshing the page before it runs out of memory?

window.setTimeout("location.reload()",1000*60*60);//refresh in an hour


Is the footprint really a problem?

I suspect that Safari caches all images as long as you stay on the same site and there's nothing you can do about it. If you're lucky Safari releases not-needed objects after some limit is reached.

The reason for this behaviour is, that Safari thinks it's likely that those images are used a second time, and therefore it caches them.



This video can help you solving your question :)
By: admin