且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Ajax调用预加载图像

更新时间:2023-12-05 10:49:22

前几天我写了一个快速插件,它将获取一系列图像URL并预加载它们,同时让您指定在每个图像加载后和/或所有图像加载完毕后要执行的操作。

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