最近需要用到预加载和延迟加载的东东,就参考写了一个。 支持跨页面,支持超时设置与依赖设置。

(function($) {
(function($) {$.preload = function(data, cfg) {return new Loader(data, cfg);};var maps = {}, on = $.event.add, un = $.event.remove, head = document.getElementsByTagName('head')[0], body =document.body, bs = $.browser, ie = bs.msie, webkit = bs.webkit, gecko = bs.mozilla, space = 1000, ajax =$.ajax,loaders = $.preload.loaders = {'js'   : function(url, callback, timeout, defer) {var s, timer;if (defer) {if (ie) {return loaders.img(url, callback, timeout);} else {s = document.createElement('object');s.data = url;s.width = s.height = 0;}} else {s = document.createElement('script');s.setAttribute('type', 'text/javascript');s.setAttribute('src', url);}function f() {if (timer)clearTimeout(timer);s.onreadystatechange = s.onload = s.onerror = null;callback(url, false);}if (ie) {s.onreadystatechange = function() {if (this.readyState === 'loaded' || this.readyState === 'complete') {if (timer)clearTimeout(timer);s.onreadystatechange = null;callback(url, true);}};} else {s.onload = function() {if (timer)clearTimeout(timer);s.onload = s.onerror = null;callback(url, true);};s.onerror = f;}timer = setTimeout(f, timeout);body.appendChild(s);},'css'  : function(url, callback, timeout, defer) {if (defer) {return loaders.js(url, callback, timeout, defer);}var s = document.createElement('link'), timer;s.setAttribute('rel', 'stylesheet');s.setAttribute('type', 'text/css');s.setAttribute('href', url);function f() {if (timer)clearTimeout(timer);s.onreadystatechange = s.onload = s.onerror = null;callback(url, false);}if (ie) {s.onreadystatechange = function() {if (this.readyState === 'loaded' || this.readyState === 'complete') {if (timer)clearTimeout(timer);s.onreadystatechange = null;callback(url, true);}};timer = setTimeout(f, timeout);} else if (webkit || gecko) {timer = new Date();function f() {if (('sheet' in s) && ('cssRules' in s.sheet)) {try {callback(url, !!s.sheet.cssRules[0]);} catch (e) {setTimeout(f, space);}} else if (new Date() - timer > timeout) {callback(url, false);} else {setTimeout(f, space);}}setTimeout(f, space * 2);} else {s.onload = function() {if (timer)clearTimeout(timer);s.onload = s.onerror = null;callback(url, true);};s.onerror = f;timer = setTimeout(f, timeout);}head.appendChild(s);},'img'  : function(url, callback, timeout) {var s = new Image(), timer;function f() {if (timer)clearTimeout(timer);s.onload = s.onerror = null;callback(url, false);}s.onload = function() {if (timer)clearTimeout(timer);s.onload = s.onerror = null;callback(url, true);};s.onerror = f;timer = setTimeout(f, timeout);s.src = url;},'ajax' : function(url, callback, cfg) {cfg = cfg || {};cfg.url = url;cfg.success = function(data) {callback(url, true, data);};cfg.error = function() {callback(url, false);};ajax(cfg);}};function Loader(data, cfg) {var self = this, cur = -1, items = [], pendings = [], done, i = 0, l = data.length, j, m, s, t, c, d, tt, item, doing =0, load;cfg = cfg || {};for (; i < l; ++i) {item = data[i];if (typeof item === 'string') {s = item.substr(item.lastIndexOf('.') + 1);items.push(maps[item] = {type : loaders[s] ? s : 'img',url  : item});} else if (item.urls) {for (j = 0, s = item.type, t = item.require, c = item.callback, d = item.defer, tt = item.timeout, item =item.urls, m = item.length; j < m; ++j) {s = s || item[j].substr(item[j].lastIndexOf('.') + 1);items.push(maps[item[j]] = {type     : loaders[s] ? s : 'img',url      : item[j],require  : t,callback : c,defer    : d,timeout  : tt});}} else {if (!item.type) {s = item.url.substr(item.url.lastIndexOf('.') + 1);item.type = loaders[s] ? s : 'img';}items.push(maps[item.url] = item);}}this.success = this.fail = this.progress = 0;if (cfg.onFinish)this.onFinish = cfg.onFinish;timeout = cfg.timeout || 2000;function callback(url, flag, data) {if (flag) {++self.success;} else {++self.fail;}self.progress = (self.success + self.fail) / items.length;console.info(url);console.warn(flag);item = maps[url];item.success = flag;if (self.progress === 1) {self.stop();}if (item.parent && !item.defer && !cfg.defer) {$(item.parent)[0].innerHTML = data || '';}if (item.callback) {item.callback(data);}item.done = true;--doing;}function runnable(item, pend) {var it;if (typeof item.require === 'string') {if (item.done)return false;if (!item.require)return true;it = maps[item.require];if (!it || it.done) {if (pend)pendings.shift();if (it && it.success) {return true;} else {callback(item.url, false);}} else if (!pend) {pendings.push(item);}} else {for (it = item.length; it--;) {if (!runnable(item[it], pend))return false;}return true;}}function run() {var item = pendings[0];if (!item || !runnable(item, true)) {while (item = items[++cur]) {if (runnable(item)) {break;}}}if (item) {var fn = loaders[item.type || 'img'];if (fn) {++doing;if (item.type === 'ajax') {if (item.cfg && !item.cfg.timeout)item.cfg.timeout = timeout;fn(item.url, callback, item.cfg);} else {fn(item.url, callback, item.timeout || timeout, item.defer === undefined ? cfg.defer: item.defer);}};if (load) {run();} else {self.timer = setTimeout(run, space);}} else if (pendings.length) {self.timer = setTimeout(run, space);}}this.start = function(delay) {if (!done)this.timer = setTimeout(run, delay > space ? delay : space);};this.stop = function() {if (this.timer) {clearTimeout(this.timer);this.timer = null;done = true;if (this.onFinish) {if (!doing)this.onFinish();else {s = setInterval(function() {if (!doing) {clearInterval(s);self.onFinish();}}, space);}}}};this.pause = function() {clearTimeout(this.timer);};this.resume = function() {this.timer = setTimeout(run, space);};this.load = function() {clearTimeout(this.timer);load = true;run();};}
})(jQuery);
/*** @example* var loader = $.preload([// 字符串,采用默认配置'1.jpg', '1.js',// 对象,自定义配置,如type, require, timeout, defer, callback{type    : 'img',url     : 'http://foo.com/foo',timeout : 10}, {url      : '3.js',callback : fn,defer    : true,require  : '1.js'},// 对象,可用urls指定一组相同配置{type : 'css',urls : ['4.css', '5.css']}], {// 加载结束后调用onFinish : fn,// 加载超时timeout  : 50});// 开始预加载loader.start();loader.stop();// 暂停预加载loader.pause();loader.resume();// 实时加载loader.load();*/

转载于:https://www.cnblogs.com/nozer0/archive/2010/05/12/1733818.html

preloadlazy load相关推荐

  1. python:Json模块dumps、loads、dump、load介绍

    20210831 https://www.cnblogs.com/bigtreei/p/10466518.html json dump dumps 区别 python:Json模块dumps.load ...

  2. 2021年大数据HBase(十五):HBase的Bulk Load批量加载操作

    全网最详细的大数据HBase文章系列,强烈建议收藏加关注! 新文章都已经列出历史文章目录,帮助大家回顾前面的知识重点. 目录 系列历史文章 HBase的Bulk Load批量加载操作 一.Bulk L ...

  3. Failed to load AppCompat ActionBar with unknown error

    复制别人demo的布局,之后没有显示界面,下面提示 Failed to load AppCompat ActionBar with unknown error 解决方法:在style 里面的 Them ...

  4. +load +initialize

    +load方法 在app启动的时候各个类的+load方法都会被调用,+load方法不是通过消息机制调用的,它是直接调用的,因此无论是在子类或者category中复写此方法,复写的+load方法都会被调 ...

  5. docker load 出错 open /var/lib/docker/tmp/docker-import-837327978/bin/json: no such file or directory

    1. 问题现象 使用 docker load 加载镜像包的时候出现如下错误: open /var/lib/docker/tmp/docker-import-837327978/bin/json: no ...

  6. python install scikit-image后,报错ImportError: DLL load failed: 找不到指定的模块

    安装: 通过pip方式成功安装后,依然报错如下图: pip install scikit-image 报错如图: Traceback (most recent call last):File &quo ...

  7. Objetive-C +load方法研究

    load方法的执行时机 Objetive-C 的runtime会在一个类的所有方法加载到内存中时调用这个类的+load() 方法,因为每个类的方法只是加载一次,所以每个+load()方法只调用一次. ...

  8. 【Qt】Ubuntu18.04下解决Qt出现qt.qpa.plugin:Could not load the Qt platform plugin “xcb“问题

    1.问题描述 在ubuntu18.04中第一次安装QT5,运行时报错 qtcreator.sh qt.qpa.plugin: Could not load the Qt platform plugin ...

  9. 【Ubuntu】制作usb启动盘安装ubuntu18.04时报错:“failed to load ldlinux.c32”

    1.问题描述 使用UltraISO制作ubuntu18.04操作系统的usb启动盘后,按照时报错: failed to load ldlinux.c32 ubuntu16.04.ubuntu14.04 ...

最新文章

  1. iOS7修改UISearchBar的Cancel按钮的颜色和文字
  2. 自定义myeclipse中的servlet模板文件
  3. 自定义ClassLoader和双亲委派机制
  4. Effective C++学习第八天
  5. IDEA全文搜索排除无用的文件夹
  6. 如何在React中使用功能组件
  7. vscode无法打开源文件iostream_C++的iostream标准库介绍(1)
  8. 关于.dll' could not be found 的问题以及解决方案
  9. OpenSTA —— 高效的 web 性能测试工具
  10. 源码文件编码问题,导致编译的程序运行错误
  11. 天锐绿盾技术大讲堂:终端出现红色“+”
  12. excel服务器模板修改,勤哲Excel服务器设计查询模板
  13. IEEE Access 模板 图片编辑
  14. PS教程:利用自定义形状快速打造图案
  15. oracle数据库外联,Oracle数据库-关于外联接
  16. python爬虫:用无头浏览器selenium爬取taptap游戏榜单并保存为csv
  17. 联想服务器出现系统恢复选项,Win10更新系统后开机提示自动修复的常规解决方案...
  18. 如何发表期刊方法步骤
  19. React中CSS样式
  20. DDL,DML,DCL

热门文章

  1. 网贷申请技巧,提高90%通过率
  2. STC单片机程序下载失败总结
  3. 64位Ubuntu kylin 16.04搭建nfs网络文件系统
  4. swift date 计算差_[Swift 设计模式] 适配器
  5. gc java root_聊聊Java的GC机制
  6. python实现ping命令_[小菜随笔]python tkinter实现简单的ping命令
  7. Random Forest 资源汇总(待续)
  8. Java编程基础阶段笔记 day 07 面向对象编程(上)
  9. Java生鲜电商平台-深入订单拆单架构与实战
  10. ListViewAutoScrollHelper