Frage

I've got a very simple piece of functionality on my site that shows a static image when the page loads and if you want to see the gif then you hit the image and it loads and starts showing once loaded.

It goes as follows

jQuery(".imgGif").each(function(index) {
jQuery(this).css( "cursor", "pointer" ); 
jQuery(this).click(function (index) {
    src = jQuery(this).attr('src');
    var extension = src.substr( (src.lastIndexOf('.') +1) );
     switch(extension) {
        case 'gif':
            jQuery(this).attr('src', src.substr(0, src.length-3) + 'jpg');
            break;
        case 'jpg': 
            jQuery(this).attr('src', src.substr(0, src.length-3) + 'gif');

            break;
        default:
            alert(extension);
            break;
        }
})
});

It works and you can see it here, http://www.lazygamer.net/xbox-360/has-watchdogs-been-downgraded-since-e3-2012/

However the gifs are 15mb so it takes a while for them to load and start playing, how do I get the image to change to a loading image while we wait so that people know something is happening?

War es hilfreich?

Lösung

replace this code:

jQuery(this).attr('src', src.substr(0, src.length-3) + 'jpg');

with:

var $el = jQuery(this);

//save the original source in a variable
var src = $el.attr('src');

//replace the current source with a loading gif (i.e. http://preloaders.net/)
jQuery(this).attr('src', '/path/to/loading.gif');

//start loading the original image
var img = new Image();

//once the original image is loaded then replace the loading gif
img.onload = function () {
    $el.attr('src', src);
}
img.src = src;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top