Preload images from an Ajax Call

前端 未结 2 513
太阳男子
太阳男子 2020-12-21 18:43

Could someone help me understand how to preload the images from random.php page so the first time it loads it fades in as it should. Currently its got an ugly bulk echo bec

2条回答
  •  不思量自难忘°
    2020-12-21 18:50

    The other day I wrote up a quick plugin that will take an array of image URLs and preload them, while letting you specify what to do after each image is loaded and/or after all the images are finished loading.

    jQuery.extend(jQuery, {
        imagesToLoad: 0,
        loadedImages: [],
        preloadImages: function(){
            var settings = {
                urls : [],
                begin : function(){},
                each : function(){},
                complete : function(){},
                scope: window
            };
            jQuery.extend(settings, arguments[0]);
            var images = [];
    
            jQuery.imagesToLoad = settings.urls.length;
    
            settings.begin.call(settings.scope, settings.urls);
            for(var i = 0; i < settings.urls.length; i++){
                images[i] = new Image();
                images[i].onload = function(){
                    settings.each.call(settings.scope,this);
                    jQuery.loadedImages.push(this);
                    if(jQuery.loadedImages.length >= jQuery.imagesToLoad){
                        settings.complete.call(settings.scope,jQuery.loadedImages);
                    }
                }
                images[i].src= settings.urls[i];
            }
        }
    });
    

    You can then use this in your code by doing something like:

    $.preloadImages({
        urls: ['path/to/image/1.jpg', 'path/to/image/2.jpg'],
        begin: function(urls){
            console.log("loading images %o", urls);
        },
        each: function(image){
            console.log("finished loading %s", image.src);
        },
        complete: function(images){
            // do whatever after all the images are done loading
        }
    });
    

提交回复
热议问题