Hi All
I’m using a double background image for a site - basically two containers around everything, one with a gif with patches of different colour, and above it a semi-opaque png with a very faint texture. I’m doing it this way as it makes for much faster loading than one jpg with the image and texture combined.
The only problem is that you see the gif load first, then the texture goes over it. Is there any way, perhaps with JS, to hide these background images until they’re both fully loaded, then display them together?
Many thanks,
Frank
This might work. If you hide your content (<body style=“display:none”>) and then preload some images using javascript, after they’re done preloading then show the <body> again. Soooo…
<body style="display:none">
Your content
</body>
<script type="text/javascript">
window.onload = function(){
// Load the 1st background image
pic1= document.createElement('src');
pic1.src="path/to/your/image1.png";
// Load the 2nd background image
pic2= document.createElement('src');
pic2.src="path/to/your/image2.png";
document.body.style.display = '';
}
</script>
The down side to using this code is that if a user has JS disabled, it will simply show nothing.
Thanks for replying!
Yep that could work. I could first hide the body with JS, so that non-JS users weren’t effected. The only downside I can see then is that the whole page has to load before anything gets displayed, which might make it seem slower than it is. Ideally I’d find a way to just not show the background images until they’re loaded. But that might be a bit optimistic…
function loadImageGroup(srcs, onGroupCompleteCallback) {
var remaining = srcs.length;
function decrementGroupCounter() {
if (--remaining == 0) {
onGroupCompleteCallback();
}
}
for (var i=0; i<srcs.length; i++) {
var img = new Image;
img.onload = img.onerror = img.onabort = decrementGroupCounter;
img.src = srcs[i];
}
}
var myContainerElement = document.getElementById("someContainer");
// remove the class that specifies the background images
myContainerElement.className = "";
loadImageGroup(["a.gif", "b.png"], function(){
// this code executed when the image group finishes loading
// add the class that specifies the background images
myContainerElement.className = "foo";
});
You would put that right before the closing </body> tag. You still want the style set up to display the images like it is right now, because not everyone has javascript enabled. For those who do, this will try to stop the display of the background images until they have all loaded(or they reported they have failed to load).
Wow, that’s very clever. Will give that a go. Thanks loads!