基于jq实现图片预加载功能

一、什么是预加载?

预加载是一种web性能优化技术,在页面加载之前,对部分资源进行提前加载,以提供给用户更好的体验,提高用户在浏览资源过程的流畅感。

二、预加载的实现

本次实验依赖jq实现

首先看一下预加载实现的效果
提前对页面中未显示的图片资源进行加载,当用户在浏览到相应的图片资源时直接从浏览器缓存中渲染在页面上。
实验效果
首先,我们使用立即执行函数,以闭包的方式,实现局部变量,避免内部变量与外部发生冲突,在内部声明Preload函数。
这里使用了Jq的extend函数深拷贝传递的对象给局部变量中

function Preload(imgs, options){
	this.imgs = imgs;
	this.opts = $.extend({}, Preload.DEFAULTS, options);
	this._unordered();
}

定义默认的对象,each表示每加载完成一次图片资源,就执行一次each中的函数;而all则当全部图片资源加载完成后执行的函数

Preload.DEFAULTS = {
	each: null,
	all: null
}

在Preload的原型对象中创建_unordered函数,用来加载图片资源,这里需要注意,监听的load和error事件是等到遍历完成后才会依次执行相应的回调函数

Preload.prototype._unordered = function(){
	var imgs = this.imgs,
		opts = this.opts,
		count = 0,
		len = imgs.length;
	//预先对图片进行加载存放在浏览器中,当页面需要显示该图片时直接从缓存中获取显示在dom上
	//过程:同步遍历完成全部imgs中的元素并给src赋值->异步执行加载图片
	$.each(imgs, function(i, src){
		if(typeof src !== 'string') return;
		var imgObj = new Image();
		$(imgObj).on('load error', function(e){
			opts.each && opts.each(count);
			if(count >= len - 1){
				opts.all && opts.all();
			}
			count++;
		});
		imgObj.src = src;
	});
}

将函数导出到需要使用的页面

//导出
$.extend({
	Preload: function(imgs, opts){
		new Preload(imgs, opts);
	}
});

html页面

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>图片预加载之无序加载</title>
		<link rel="stylesheet" type="text/css" href="index.css"/>
	</head>
	<body>
		<div class="loading">
			<span class="progress">0%</span>
		</div>
		<div class="box">所有图片加载完成!!</div>
		<script src="js/jquery-1.9.0.min.js"></script>
		<script src="js/preload.js"></script>
		<script>
			var imgs = [];
			var index = 0,
				len = imgs.length,
				$progress = $('.loading > span');
				
			$.Preload(imgs, {
				each: function(count){
					$progress.html(Math.round((count + 1) / len * 100) + '%');
				},
				all: function(){
					$('.loading').hide();
					document.title = '1/' + len;
				}
			});
		</script>
	</body>
</html>

最终preload.js代码

(function($){
	function Preload(imgs, options){
		this.imgs = imgs;
		this.opts = $.extend({}, Preload.DEFAULTS, options);
		
		this._unordered();
	}
	
	Preload.DEFAULTS = {
		each: null,
		all: null
	}
	
	Preload.prototype._unordered = function(){
		var imgs = this.imgs,
			opts = this.opts,
			count = 0,
			len = imgs.length;
		//预先对图片进行加载存放在浏览器中,当页面需要显示该图片时直接从缓存中获取显示在dom上
		//过程:同步遍历完成全部imgs中的元素->异步执行加载对于图片
		$.each(imgs, function(i, src){
			if(typeof src !== 'string') return;
			var imgObj = new Image();
			$(imgObj).on('load error', function(e){
				opts.each && opts.each(count);
				if(count >= len - 1){
					opts.all && opts.all();
				}
				count++;
			});
			imgObj.src = src;
		});
	}
	
	$.extend({
		Preload: function(imgs, opts){
			new Preload(imgs, opts);
		}
	});
	
})(jQuery)

(本文纯属个人学习笔记,如有不足请留言!)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章