Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something if an image is not loaded (jquery)

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:

  1. Check if a background image is already in the cache.
  2. If it is then show it.
  3. If it isn't then hide it and when it loads, fade it in.

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

});
like image 547
Learnz Avatar asked Nov 05 '22 07:11

Learnz


1 Answers

You can try:

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

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

like image 114
karim79 Avatar answered Nov 13 '22 18:11

karim79