Javascript图片预加载
来源:互联网 发布:js防水涂料是什么意思 编辑:程序博客网 时间:2024/04/27 22:01
Javascript图片预加载
在遇到图片很多的时候,使用图片预加载可以避免在交互展示中所造成的一些麻烦,比如图片背景切换闪烁问题。
简单版本:
// 图片预加载var preloadImages = [];function preload() { for (i = 0; i < preload.arguments.length; i++) { preloadImages[i] = new Image(); preloadImages[i].src = preload.arguments[i]; }}
调用例子:
// 调用preload( window.basepath +"/answer_bg1_1.png", window.basepath +"/answer_bg2_1.png");
复杂版本:
/** * 图片头数据加载就绪事件 - 更快获取图片尺寸 * @param {String} 图片路径 * @param {Function} 尺寸就绪 * @param {Function} 加载完毕 (可选) * @param {Function} 加载错误 (可选) * @example imgReady('http://www.google.com.hk/intl/zh-CN/images/logo_cn.png', function () { alert('size ready: width=' + this.width + '; height=' + this.height); }); */var imgReady = (function () { var list = [], intervalId = null, // 用来执行队列 tick = function () { var i = 0; for (; i < list.length; i++) { list[i].end ? list.splice(i--, 1) : list[i](); }; !list.length && stop(); }, // 停止所有定时器队列 stop = function () { clearInterval(intervalId); intervalId = null; }; return function (url, ready, load, error) { var onready, width, height, newWidth, newHeight, img = new Image(); img.src = url; // 如果图片被缓存,则直接返回缓存数据 if (img.complete) { ready.call(img); load && load.call(img); return; }; width = img.width; height = img.height; // 加载错误后的事件 img.onerror = function () { error && error.call(img); onready.end = true; img = img.onload = img.onerror = null; }; // 图片尺寸就绪 onready = function () { newWidth = img.width; newHeight = img.height; if (newWidth !== width || newHeight !== height || // 如果图片已经在其他地方加载可使用面积检测 newWidth * newHeight > 1024 ) { ready.call(img); onready.end = true; }; }; onready(); // 完全加载完毕的事件 img.onload = function () { // onload在定时器时间差范围内可能比onready快 // 这里进行检查并保证onready优先执行 !onready.end && onready(); load && load.call(img); // IE gif动画会循环执行onload,置空onload即可 img = img.onload = img.onerror = null; }; // 加入队列中定期执行 if (!onready.end) { list.push(onready); // 无论何时只允许出现一个定时器,减少浏览器性能损耗 if (intervalId === null) intervalId = setInterval(tick, 40); }; };})();
调用例子:
imgReady(window.basepath +"/answer_bg1_1.png", function () { alert('size ready: width=' + this.width + '; height=' + this.height);});
0 0
- javascript图片预加载
- Javascript图片预加载
- Javascript之预加载图片
- JavaScript实现图片预加载
- javascript图片预加载技术
- javascript图片预加载技术
- javascript图片预加载技术
- javascript图片预加载技术
- javascript图片预加载技术
- Javascript图片预加载详解
- Javascript图片预加载详解
- Javascript图片预加载详解
- Javascript图片预加载详解
- Javascript图片预加载详解
- Javascript图片预加载详解
- javascript 图片 懒加载、预加载
- 【JavaScript】JavaScript实现图片翻转以及预加载图片
- JavaScript图片预加载代码,显示loading
- Docker的常规应用手册
- Node.js下使用Redis
- Android Studio中gradle介绍(一)
- maven下添加oracle.jar
- js中继承
- Javascript图片预加载
- Ajax传输XML
- js计时器
- Leetcode / C++ / 475. Heaters 解题报告+源代码
- 打造简洁高效的动态权限管理器
- Article on 梯度消失/Ensemble Modeling/Batch Normalization
- JavaScript性能监控器
- Linux查看端口、进程情况及kill进程
- js本地存储