Search code examples
jquerycachingloadingimage-gallery

Jquery .Load Image, How to check if the image is already loaded in the browser?


I wrote a simple script to load the image in to the main viewer. Its very simple, click thumbnail - grab the gallery id and the image id.. pass these in to the .load, new content is loaded.

At the moment if you click a thumb the image is loaded, and if you click the same thumb again it calls the image again, I don't want this. I want to be able to check if the image is already loaded in the browser cache and if so to not execute the .load

Thanks for reading this, any help would be appreciated.

$('#thumb_list li a').click(function(){

var gallery_id = $(this).attr('gallery');
var image_id = $(this).attr('rel');

$("#image_container")
         .load("inc_photos.cfm?gallery_id=" + gallery_id + "&image_id=" + image_id,
         function(){

         });
return false;
});

Solution

  • There's a couple of things you can do. First, you can simply remove the click even from the image if you don't want it to be able to be clicked again after it tries to load.

    $('#thumb_list li a').click(function(){
    
    var gallery_id = $(this).attr('gallery');
    var image_id = $(this).attr('rel');
    
    $("#image_container")
             .load("inc_photos.cfm?gallery_id=" + gallery_id + "&image_id=" + image_id,
             function(){
                 $('#thumb_list li a').unbind('click');
             });
    return false;
    });
    

    However, if you want to do something else with the same click method, then you might want to add a flag to check if it has already been loaded. You can do this in 2 places if you're having problems with it.

    var isImageLoaded = false;
    
    $('#thumb_list li a').click(function(){
    
    var gallery_id = $(this).attr('gallery');
    var image_id = $(this).attr('rel');
    if( !isImageLoaded )
    {
        $("#image_container")
             .load("inc_photos.cfm?gallery_id=" + gallery_id + "&image_id=" + image_id,
             function(){
                 isImageLoaded = true;
             });
    }
    return false;
    });
    

    You can also do it on click if you want to avoid any duplicate network traffic:

    var isImageLoaded = false;
    
    $('#thumb_list li a').click(function(){
    
    var gallery_id = $(this).attr('gallery');
    var image_id = $(this).attr('rel');
    
    if( !isImageLoaded )
    {
        $("#image_container")
             .load("inc_photos.cfm?gallery_id=" + gallery_id + "&image_id=" + image_id,
             function(){
    
             });
    }
    isImageLoaded = true;
    return false;
    });