Preload images from an Ajax Call

一曲冷凌霜 提交于 2019-11-29 15:43:37

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

Here's a trick that I like: on a page before random.php add at the bottom of the page an img tag which references the image you want to fade in on random.php. Add to the img tag a CSS class which is simply display: none. This will prime the user's browser cache with the image so that when they do go to random.php the image was already downloaded and your fade works as expected. Of course this only works if random.php isn't the site landing page. Another factor is how many images you're talking about and their size.

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