I have seen some code to check if a background image on a div is loaded. What they are doing is adding a img tag to memory but storing it in a variable and using that to see if the image is loaded with the load event. My question is does the $img tag stay in memory and how would I be able to remove that tag when the load event has been called.
var $div = $('div'),
bg = $div.css('background-image');
if (bg) {
var src = bg.replace(/(^url\()|(\)$|[\"\'])/g, ''),
$img = $('<img>').attr('src', src).on('load', function() {
// do something, maybe:
$div.fadeIn();
});
}
});
You can remove elements with remove(). In your case the newly created
<img>element is cached in the$imgvariable. So when you want to remove it you just do:To release the variable from memory you can use:
Although that isn’t really necessary if the variable scope is not global as the javascript garbage collector will take care of that for you.
Also load() is deprecated and unreliable across browsers, so using it is discouraged. From jQuery docs:
One alternative to load is this plugin.