JavaScript Preload Images

孤人 提交于 2019-12-03 14:42:33

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

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

Made Something and Added images 10 images. They Load without any hustle and bustle. I just tried it on my internet which is slow tortoise.

I think browser waits until all images of your function is completed as you have $(document).ready( function() { });.

Fiddle

var i = 1;
$(document).ready(function(){
    $(window).stop();
    $("img").hide();
    $("img").each(function(){
        var source = $(this).attr("src");
        var img = new Image();
        img.className = i;
        img.src = source;
        $('body').append(img);
        $("."+i).hide().fadeIn();
        i++;
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!