【问题标题】:Preload images from an Ajax Call从 Ajax 调用中预加载图像
【发布时间】:2010-12-13 02:16:01
【问题描述】:

有人可以帮助我了解如何从 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");
        });
      });
    }
  });
}

【问题讨论】:

    标签: jquery image preload


    【解决方案1】:

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

    【讨论】:

    【解决方案2】:

    这是我喜欢的一个技巧:在random.php 之前的页面上,在页面的底部 处添加一个img 标记,该标记引用您要在random.php 上淡入的图像。向 img 标签添加一个简单的 CSS 类 display: none。这将使用图像填充用户的浏览器缓存,以便当他们进入 random.php 时,图像已经下载并且您的淡入淡出按预期工作。当然,这仅在 random.php 不是站点登录页面时才有效。另一个因素是您正在谈论的图片数量及其大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 2012-06-06
      • 2011-07-07
      • 2015-02-27
      相关资源
      最近更新 更多