Skip to content

Instantly share code, notes, and snippets.

@asawilliams
Created November 2, 2011 15:18
Show Gist options
  • Save asawilliams/1333892 to your computer and use it in GitHub Desktop.
Save asawilliams/1333892 to your computer and use it in GitHub Desktop.
Delays the background image displaying until loaded. After loaded it will then fade out the overlay to display the background image. This is used for larger image file sizes. This code represents a proof of concept.
#bg-overlay {
position: absolute;
top: 0;
height: 100%;
width: 100%;
background-color: #444; /* What ever you want to the default background to look like before the image is displayed */
z-index: -1;
}
.bg-img {
background-image: url('http://www.location/of/really/big/image.jpg');
}
<html>
<body>
<!-- This overlay should be at the top -->
<div id="bg-overlay">
<!-- Temporary background overlay until image is downloaded -->
</div>
</body>
</html>
// requires: Modernizr, jQuery, and the jQuery cookie plugin
// allow this object to be global and placed in the root/base template
var gBackground = (function() {
// if the background image has been previously loaded, just remove overlay and apply image
function checkImgCookie() {
if($.cookie('bgImageLoaded')) {
$('body').addClass('bg-img');
$('#bg-overlay').remove();
}
}
// call this (gBackground.loadBgImg()) on each page when you want it to start loading
// recommend putting this in document ready.
function loadBgImg() {
if($.cookie('bgImageLoaded') || $('body').hasClass('bg-img')) return;
Modernizr.load({
load:"http://www.location/of/really/big/image.jpg",
complete: function() {
$('body').addClass('bg-img');
$('#bg-overlay').fadeOut(4000, function() {$(this).remove();});
$.cookie('bgImageLoaded', true, {expires: 7, path:'/'});
}
});
}
return {loadBgImg: loadBgImg, checkImgCache: checkImgCookie};
})();
gBackground.checkImgCache();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment