jQuery ajax images preload

此生再无相见时 提交于 2019-12-11 22:07:46

问题


Given this, which preloads an image:

$('<img />')
    .attr('src', 'source')
    .load(function(){
        $('.profile').append( $(this) );
        // Your other custom code
    });

do you know how to do the same but for several images?

I tried something like :

var img1 = new Image();
var img2 = new Image();
$(img1).attr('src', 'source1');
$(img2).attr('src', 'source2');

$(img1,img2).load(
 function () {
  //code after loading
 }
);

but it doesn't work!

Any ideas?


回答1:


FINAL ATTEMPT

As far as I can tell you want to be able to tell when the image loads, and do it multiple times. The problem with the previous attempt, and your own code, is that the "load" handler is only applied AFTER the new image source has been set and executed. Please, try this on for size:

$(function () {
    var images = ['image1.jpg','image2.jpg' /* ... */ ];
    var imageObjects = [];
    var imagesToLoad = 0;

    for (i = 0, z = images.length; i < z; i++) {
        imageObjects[i] = new Image();
        imagesToLoad++;
        $(imageObjects[i])
            .load(function () {
                if (--imagesToLoad == 0) {
                    // ALL DONE!
                }
                // anything in this function will execute after the image loads
                var newImg = $('<img />').attr('src',$(this).attr('src'));
                $('.profile').append( $(newImg) ); // I assume this is the code you wanted to execute
            })
            .attr('src',images[i]);
            // Notice that the 'attr' function is executed AFTER the load handler is hooked
    }
});

[OLD] NEW ATTEMPT

var images = [ /* you get it by now */ ];
for (i=0,z=images.length;i<z;i++) {
    $('<img />')
        .attr('src', images[i])
        .load(function(){
            $('.profile').append( $(this) );
            // Your other custom code
        });
}

ORIGINAL POST

Idea taken from This Article

$(document).ready(function(){
    var images = ["image1.jpg","image2.jpg"];
    var loader = new Image();

    for (i=0,z=images.count;i<z;i++) {
        loader.src = images[i];
        // insert some code here to do something with the now-loaded image
    }
    // do something with the now-loaded images.
});

Alternatively,

var images = ["image1.jpg","image2.jpg"];
var loader = [];
$(document).ready(function(){

    for (i=0,z=images.count;i<z;i++) {
        loader[i] = new Image();
        loader[i].src = images[i];
        // insert some code here to do something with the now-loaded image
    }
    // do something with the now-loaded images, using the loader array
});



回答2:


You need to create an array of elements:

$(img1,img2).load(

should be

$([img1, img2]).load(

It seems like overkill to do $(img1).attr('src', 'source1'); when you could do img1.src = 'source1';




回答3:


Load is triggered when you set the 'src' attribute. You must register the event before you set the 'src' attribute. Try this:

var img1 = new Image(); 
var img2 = new Image(); 
$([img1,img2]).load( function () { //code after loading } );
$(img1).attr('src', 'source1');
$(img2).attr('src', 'source2'); 

Hope this helps!

UPDATED

var images = [ /* you get it by now */ ];
for (i=0,z=images.length;i<z;i++) {
$('<img />')
  .load(function(){
    $('.profile').append( $(this) );
    // Your other custom code
  })  
  .attr('src', images[i]);
  /* you may also try to add .trigger('load') at the end to force it */
}

-Stephen




回答4:


function myfun(){
  alert("h");
} 

var xlist = [ "source1", "source2", "source3" ];
var xload = 0;
$.each(xlist, function(){
    var srcImg = this;
    $('<img />')
       .attr('src', srcImg)
       .load(function(){
           xload++;
           $('.profile').append( $(this) );
           if (xlist.length==xload){

             // Your other custom code
             myfun();  

           }
       });
});

for comment: could simply be controlling the total amount of pictures loaded.




回答5:


I recently went through this nightmare. There are a couple StackOverflow questions where I mentioned the frustrating problems with the image load event.

One way that actually works cross-browser is to use a timer and watch both the image complete property (until it is true) and the image width property (until it is non-zero). Just spin through all your images until that pair of requirements is true for all of them.

Or you could try Luke Smith's solution.



来源:https://stackoverflow.com/questions/1798995/jquery-ajax-images-preload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!