Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Preload Images

I am trying to preload images, the following code works:

$(document).ready(function(){
    $(".member-photos img").each(function(){
        var id = $(this).attr("data-id");
        var file = $(this).attr("data-file");
        var img = new Image();
        img.src = "/user-data/images/image.php?id="+id+"&file="+file+"&width=600&crop=false";
    });
});

But the issue I would like to solve, is that Chrome displays the spinning "Loading" icon in the tab. Is there a way I can do this so it doesn't continuously spin until the images have loaded? I would like for the page and thumbnails to load then start loading the larger images in the background without the spinning icon in the tab.

like image 502
Get Off My Lawn Avatar asked Feb 14 '13 04:02

Get Off My Lawn


2 Answers

Have not tested my thoughts yet.

I think you are loading image files synchronously when document is ready, so Chrome tells user that loading is not done.

Not to show the spinning image, you should use ajax call to server to receive images and you can add it to document or do nothing(since it's already cached)

$.ajax({ url : <<image_url>>, cache: true, processData : false, })
.success(function(){ 
  $(document).append( $("<img/>").attr("src", <<image_url>>).hide() );
});
like image 182
allenhwkim Avatar answered Oct 09 '22 02:10

allenhwkim


Using ajax part of bighostkim's answer, and the load() event, I got what I wanted

To achieve the desired results, the each loop needed to be within the load() event. Placing it in the ready() event causes the images to start to load before the page images, causing the page images to pend in the queue and load after the preloaded images. Most browsers only allow for a few items to load from the same host simultaneously, the others must wait till a spot opens up (unless it is from a different host).

$(window).load(function(){
    $(".member-photos img").each(function(){
        var id = $(this).attr("data-id");
        var file = $(this).attr("data-file");
        $.ajax({ url : "/user-data/images/image.php?id="+id+"&file="+file+"&width=600&crop=false", cache: true, processData : false });
    });
});
like image 44
Get Off My Lawn Avatar answered Oct 09 '22 03:10

Get Off My Lawn