I'm looking to fade in the background image when a visitor arrives at the site but not when they've already got that image in their cache. Something along the lines of this:
Using jQuery I can hide it and then fade it in when it loads:
$("#bkg img").hide();
$('#bkg img').load(function() {
$(this).fadeIn();
});
But how do I make this conditional so it only happens if the image isn't already cached?
Everything I've found on forums triggers when an image finishes loading. How can I get it to trigger because it isn't loaded?
Thanks for any help, Lernz
@Sima Based on code from that other thread I've made it as far as the following - but it doesn't seem to be having any effect. If you can see where I'm going wrong that'd be great:
var storage = window.localStorage;
if (!storage.cachedElements) {
storage.cachedElements = "";
}
function logCache(source) {
if (storage.cachedElements.indexOf(source, 0) < 0) {
if (storage.cachedElements != "")
storage.cachedElements += ";";
storage.cachedElements += source;
}
}
function cached(source) {
return (storage.cachedElements.indexOf(source, 0) >= 0);
}
var plImages;
//On DOM Ready
$(document).ready(function() {
plImages = $("#fundo-1 img");
//log cached images
plImages.bind('load', function() {
logCache($(this).attr("src"));
});
//display cached images
plImages.each(function() {
var source = $(this).attr("src")
if (!cached(source)) {
$(this).hide().fadeIn();
}
});
});
You can try:
if(!$('#bkg img')[0].complete) {
$('#bkg img').hide().load(function () {
$(this).fadeIn();
});
}
https://developer.mozilla.org/en/DOM/HTMLImageElement
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With