How to Lazy Load div background images
First you need to think off when you want to swap. For example you could switch everytime when its a div tag thats loaded. In my example i just used a extra data field "background" and whenever its set the image is applied as a background image.
Then you just have to load the Data with the created image tag. And not overwrite the img tag instead apply a css background image.
Here is a example of the code change:
if (settings.appear) { var elements_left = elements.length; settings.appear.call(self, elements_left, settings);}var loadImgUri;if($self.data("background")) loadImgUri = $self.data("background");else loadImgUri = $self.data(settings.data_attribute);$("<img />") .bind("load", function() { $self .hide(); if($self.data("background")){ $self.css('backgroundImage', 'url('+$self.data("background")+')'); }else $self.attr("src", $self.data(settings.data_attribute)) $self[settings.effect](settings.effect_speed); self.loaded = true; /* Remove image from array so it is not looped next time. */ var temp = $.grep(elements, function(element) { return !element.loaded; }); elements = $(temp); if (settings.load) { var elements_left = elements.length; settings.load.call(self, elements_left, settings); } }) .attr("src", loadImgUri );}
the loading stays the same
$("#divToLoad").lazyload();
and in this example you need to modify the html code like this:
<div data-background="http://apod.nasa.gov/apod/image/9712/orionfull_jcc_big.jpg" id="divToLoad" />
but it would also work if you change the switch to div tags and then you you could work with the "data-original" attribute.
Here's an fiddle example: http://jsfiddle.net/dtm3k/1/
I do it like this:
<div class="lazyload" style="width: 1000px; height: 600px" data-src="%s"> <img class="spinner" src="spinner.gif"/></div>
and load with
$(window).load(function(){ $('.lazyload').each(function() { var lazy = $(this); var src = lazy.attr('data-src'); $('<img>').attr('src', src).load(function(){ lazy.find('img.spinner').remove(); lazy.css('background-image', 'url("'+src+'")'); }); });});
I've found this on the plugin's official site:
<div class="lazy" data-original="img/bmw_m1_hood.jpg" style="background-image: url('img/grey.gif'); width: 765px; height: 574px;"></div>$("div.lazy").lazyload({ effect : "fadeIn"});
Source: http://www.appelsiini.net/projects/lazyload/enabled_background.html