Wait for Background Images in CSS to Be Fully Loaded

Wait For Image To Be Loaded Before Displayed

Start with visibility:hidden and change it to visibility:visible on the image's onload event handler.

edit: example

In your HTML, have:

<img onload="imgLoad(this)" style="visibility:hidden" ... />

In your script, have:

function imgLoad(img) {
img.style.visibility='visible';
}

Wait for image to be fully loaded before displayed on page?

What comes to mind without actually used or tested it is wrapping the image. I'll use jQuery for the sample

<div class="loading"><img/></div>

CSS could be

.loading { display: inline-block; }
.ie6 .loading, .ie7 .loading { display: inline; } /* these could be set by http://www.modernizr.com/ */
.loading img {
visibility: hidden;
background: url('path/to/loading.gif') center center no-repeat transparent;
vertical-align: bottom; /* or display: block; to kill the inline white space */
}

JavaScript (jQuery)

  $(function(){
$('.loading img').load(function(){
$(this).css('visibility','visible');
});
});

Display page when all background images are loaded

You could show an overlay with loading animation

<div id="preloader"></div>

#preloader
{
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
z-index: 9999;
background: #FFFFFF url('URL TO AN ANIMATED LOADING GIF') no-repeat center center;
}

and set it to display: none after all content is loaded

window.onload = function() {
document.querySelector('#preloader').style.display = "none";
};

JQuery bind event when CSS background-image is fully loaded

You could use my jQuery plugin called waitForImages that would help with this...

$("#box").css("background-image", "url(image.php)").waitForImages({
waitForAll: true,
finished: function() {
// Background image has loaded.
}
});

Otherwise, to do it manually...

var image = 'image.php',

img = $('<img />');

img.bind('load', function() {
// Background image has loaded.
});

img.attr('src', image);

$('#box').css('background-image', 'url(' + image + ')');


Related Topics



Leave a reply



Submit