Reputation: 6625
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();
});
}
});
I got this code above from this post
Upvotes: 1
Views: 1667
Reputation: 146201
Just set the $img
variable null
, like
$img=null;
Actually $img.remove();
won't do that as mentioned in the comment by someone and also you don't have to worry about it because javascript Garbage Collector will do it for you and delete
will work only if you declare the variable without var
keyword. In this case of $img=null
just makes the variable an empty null
object.
Example using null and Example using .remove().
Upvotes: 0
Reputation: 44526
You can remove elements with remove(). In your case the newly created <img>
element is cached in the $img
variable. So when you want to remove it you just do:
$img.remove();
To release the variable from memory you can use:
delete $img;
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:
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
• It doesn't work consistently nor reliably cross-browser
• It doesn't fire correctly in WebKit if the image src is set to the same src as before
• It doesn't correctly bubble up the DOM tree
• Can cease to fire for images that already live in the browser's cache
One alternative to load is this plugin.
Upvotes: 2