几个使用jQuery的图片预加载函数


最近项目中用到的一个功能,用户进入网站时显示loading页面,直到主页的几个大图片加载完成才渐隐进入主页。自己写了个插件,看起来结构挺糟糕的,不好意思放到项目里。在网上搜现成的,还挺多。不过得用英文关键词,搜中文的真是垃圾网站一大堆。废话完毕下面开始

第一个

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

使用方法

jQuery.preLoadImages("image1.gif", "/path/to/image2.png");

这个来自这里:Engineered Web。可以看到其实这个是用原生JavaScript实现,使用jQuery是为了调用方便。
优点:原生JavaScript,速度快。
缺点:不支持回调函数。

第二个

// Helper function, used below.
// Usage: ['img1.jpg','img2.jpg'].remove('img1.jpg');
Array.prototype.remove = function(element) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == element) { this.splice(i,1); }
  }
};

// Usage: $(['img1.jpg','img2.jpg']).preloadImages(function(){ ... });
// Callback function gets called after all images are preloaded
$.fn.preloadImages = function(callback) {
  checklist = this.toArray();
  this.each(function() {
    $('<img>').attr({ src: this }).load(function() {
      checklist.remove($(this).attr('src'));
      if (checklist.length == 0) { callback(); }
    });
  });
};

使用方法

$.post('/submit_stuff', { id: 123 }, function(response) {
  $([response.imgsrc1, response.imgsrc2]).preloadImages(function(){
    // Update page with response data
  });
});

第二个函数来自 stackoverflow
这个支持了回调函数,全部图片都加载完成后执行,我的项目中就是用的这个。
作者为了方便扩展了Array对象,使用时注意不要影响到其他的代码。
搜索的时候还发现一个更好用的:

第三个

(function($) {
	var imgList = [];
	$.extend({
		preload: function(imgArr, option) {
			var setting = $.extend({
				init: function(loaded, total) {},
				loaded: function(img, loaded, total) {},
				loaded_all: function(loaded, total) {}
			}, option);
			var total = imgArr.length;
			var loaded = 0;

			setting.init(0, total);
			for(var i in imgArr) {
				imgList.push($("<img />")
					.attr("src", imgArr[i])
					.load(function() {
						loaded++;
						setting.loaded(this, loaded, total);
						if(loaded == total) {
							setting.loaded_all(loaded, total);
						}
					})
				);
			}

		}
	});
})(jQuery);

调用方法:

$(function() {
    $.preload([
        "http://farm3.static.flickr.com/2661/3792282714_90584b41d5_b.jpg",
        "http://farm2.static.flickr.com/1266/1402810863_d41f360b2e_o.jpg"
    ], {
        init: function(loaded, total) {
            $("#indicator").html("Loaded: "+loaded+"/"+total);
        },
        loaded: function(img, loaded, total) {
            $("#indicator").html("Loaded: "+loaded+"/"+total);
            $("#full-screen").append(img);
        },
        loaded_all: function(loaded, total) {
            $("#indicator").html("Loaded: "+loaded+"/"+total+". Done!");
        }
    });
});

这个来自这里 http://ditio.net,貌似是作者的一个插件中的一段代码。
支持三个回调函数:加载前、单个图片加载完成、全部图片加载完成。原作者还给了个演示网页,看演示网页的源代码就明白了。