jquery – 从Ajax调用预加载图像

前端之家收集整理的这篇文章主要介绍了jquery – 从Ajax调用预加载图像前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以帮我理解如何从random.PHP页面预加载图像,这样它第一次加载它就会褪色.目前它有一个丑陋的体积回声,因为它们没有被预加载,但一旦页面运行一旦它在另一个完全消失之后…
//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并预加载它们,同时让你指定在每个图像加载后和/或所有图像加载完毕后要做什么.
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];
        }
    }
});

然后,您可以通过执行以下操作在代码中使用此代码

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

猜你在找的jQuery相关文章