Just start them with visibility:hidden
and show them when the window.load
event fires.
CSS
.loading li{
visibility:hidden;
}
HTML
<article class="loading">
<ul>
<li><!-- background-image--></li>
<li><!-- background-image--></li>
</ul>
</article>
and jQuery
$(window).load(function(){
$('article.loading').removeClass('loading');
});
If you want to show the images in each article as its own images have loaded then your code is pretty close, but you can improve with the following
- handle the
error
event as well - cache your selections
- bind the
load
anderror
events before setting thesrc
to correctly handle cached images
Here is an implementation
$(function () {
var articles = $('article').addClass('loading');
var urlRegExp = /(url\([\'\"]?)([^\'\"]+)/gi;
articles.each(function(){
var article = $(this),
images = $('li', article).map(function(){
return $(this).css('background-image').split(urlRegExp)[2];
}).get(),
imageCount = images.length;
$.each(images, function(index, url){
var img = new Image();
$(img).on('load error', function(){
imageCount--;
if (imageCount === 0){
article.removeClass('loading');
}
})[0].src = url;
});
});
});
Demo at http://jsfiddle.net/gaby/2ATHQ/