It’s age old question of how to preload css background images, but with a little twist: the background images are being set via jQuery as they are from Vimeo. Each background image is a video image from vimeo, so I’m setting the background using the vimeo thumbnail url when the site loads. Can I somehow preload these images? I have an overlay in place that I want to disappear when the content is loaded, but despite my efforts, the background images are still visibly loading when the overlay disappears!
Here is some (not so eloquent) code that I’ve tried:
var count = $('.video_stub').length;
$('.video_stub').each(function(index) {
var bgUrl = $(this).data('thumb');
$('<img/>')[0].src = bgUrl;
if(index == (count - 1)) {
$('.video_stub').each(function(i) {
var bgUrl = $(this).data('thumb');
// Set the video thumb's background using the vimeo thumb image
$(this).css('background-image', 'url(' + bgUrl + ')');
if(index == (count - 1)) {
$('#temp_overlay').fadeOut('slow');
}
});
}
});
Any ideas? Thanks so much in advance.
EDIT:
I tried this code, but with no success. I’m wondering if it’s a scope issue? Maybe I’m not able to access the index variable from within the load callback:
// Set video thumb click handler
var count = $('.video_stub').length;
// Set video thumb click handler
// Iterate through each video stub
$('.video_stub').each(function(index) {
var bgUrl = $(this).data('thumb');
$('<img/>').attr('src', bgUrl).load(function() {
$('.video_stub:eq(' + index + ')').css('background-image', 'url(' + bgUrl + ')');
});
if(index == (count - 1)) {
$('#temp_overlay').fadeOut('slow');
}
});
I tried:
$('<img/>').attr('src', bgUrl).load(function() {
$(this).css('background-image', 'url(' + bgUrl + ')');
});
to no avail.
I was using queryLoader2 as my preloader, which parses through images and background images on the site. However, I was adding in some of the background images via javascript (instead of writing them into the css or into the style tag of each element) so the preloader couldn’t actually load these images.
After I changed the code in a way that included the background image attribute in each element’s “style” tag, I was able to load the images successfully!