从Ajax调用预加载图像 [英] Preload images from an Ajax Call

查看:108
本文介绍了从Ajax调用预加载图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以帮我理解如何从random.php页面预加载图像,这样第一次加载它就会褪色。目前它有一个丑陋的体积回声,因为它们没有预先加载,但一旦页面运行一旦它在另一个完全消失之后就会消失...

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 because they're not preloaded but once the page has been run once it fades on after the other perfectly...

//Loop through the images and print them to the page
for (var i=0; i < totalBoxes; i++){
  $.ajax({
    url: "random.php?no=",
    cache: false,
    success: function(html) {
      // following line I originally suggested, but let's make it better...
      //$('#bg').append(html).fadeIn('slow');
      // also note the fine difference between append and appendTo.
      var $d = $(html).hide().appendTo('#bg').fadeIn('slow');
      $('img', $d).hover(function() {
        var largePath = $(this).attr("rel");
        $(this).fadeOut("slow", function() {
          $(this).attr({ src: largePath }).fadeIn("slow");
        });
      });
    }
  });
}


推荐答案

前几天我写了一个快速插件,它将获取一系列图像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
    }
});

这篇关于从Ajax调用预加载图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆