Is there a way, using jQuery, to trigger an event on load of a CSS background image?
By default Lazy will use <img /> tags to load the src attribute. But there is also a way now to use Lazy with other html tags and load the image by background-image CSS attribute. Just use Lazy the way you would do on normal image tags. $(function() { $('.
What is Image Lazy Loading? Lazy Loading Images is a set of techniques in web and application development that defer the loading of images on a page to a later point in time - when those images are actually needed, instead of loading them up front.
you could do it like this,
$('<img>').load(function(){
// make sure to bind the load event BEFORE setting the "src"
alert('image loaded');
}).attr('src',function(){
var imgUrl = $('body').css('background-image');
imgUrl = imgUrl .substring(4, imgUrl .length-1);
return imgUrl;
}).each(function() {
// fail-safe for cached images which sometimes don't trigger "load" events
if(this.complete) $(this).load();
});
$('<img>').attr('src',function(){
var imgUrl = $('#body').css('background-image');
imgUrl = imgUrl .substring(5, imgUrl .length-2);
return imgUrl;
}).load(function(){
//Do Something
});
Could not help but notice that the above code does not work in fiddle. Looks like its because it returns "url('/img-path.jpg')" instead of just "/img-path.jpg".
However this method still fails in IE. Anyone have an ie fix?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With