Do something if image is not uploaded (jquery)

I want to disappear in the background image when the visitor comes to the site, but not when they already have this image in the cache. Something like that:

  • Make sure the background image is already in the cache.
  • If so, show it.
  • If this is not the case, hide it, and when it boots up, fade it out.

Using jQuery, I can hide it and then extinguish it on boot:

$("#bkg img").hide();

$('#bkg img').load(function() {  
 $(this).fadeIn();  
});

But how can I make it conditional so that this happens only if the cached image was not ?

Everything I found on the forums starts when the image finishes loading. How can I make it run because it is not loaded?

Thanks for any help, Lernz

@Sima , , , . , , :

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();
     }
    });

});
+5
3

:

if(!$('#bkg img')[0].complete) {
    $('#bkg img').hide().load(function () {  
        $(this).fadeIn();  
    });
}

https://developer.mozilla.org/en/DOM/HTMLImageElement

+2
$("#bkg img").hide();    
var imgCount=$("#bkg img").length;
$('#bkg img').load(function(){
    if(!--imgCount){
        $('#bkg img').fadeIn();
            // your code after load
    } else {
        // your code onloading time
    }
});
0

I think this is not as easy as it seems, there should be a solution ..

0
source

All Articles