function preloader() {if (document.images) {var img1 = new Image();var img2 = new Image();var img3 = new Image();img1.src = https://www.isolves.com/it/cxkf/yy/js/2022-01-04/"http://domain.tld/path/to/image-001.gif";img2.src = "http://domain.tld/path/to/image-002.gif";img3.src = "http://domain.tld/path/to/image-003.gif";}}function addLoadEvent(func) {var oldonload = window.onload;if (typeof window.onload != 'function') {window.onload = func;} else {window.onload = function() {if (oldonload) {oldonload();}func();}}}addLoadEvent(preloader);方法三:使用Ajax实现预加载上面所给出的方法似乎不够酷,那现在来看一个使用Ajax实现图片预加载的方法 。该方法利用DOM,不仅仅预加载图片,还会预加载CSS、JavaScript等相关的东西 。使用Ajax,比直接使用JavaScript,优越之处在于JavaScript和CSS的加载不会影响到当前页面 。该方法简洁、高效 。
window.onload = function() {setTimeout(function() {// XHR to request a js and a CSSvar xhr = new XMLHttpRequest();xhr.open('GET', 'http://domain.tld/preload.js');xhr.send('');xhr = new XMLHttpRequest();xhr.open('GET', 'http://domain.tld/preload.css');xhr.send('');// preload imagenew Image().src = https://www.isolves.com/it/cxkf/yy/js/2022-01-04/"http://domain.tld/preload.png";}, 1000);};上面代码预加载了“preload.js”、“preload.css”和“preload.png” 。1000毫秒的超时是为了防止脚本挂起,而导致正常页面出现功能问题 。
下面,我们看看如何用JavaScript来实现该加载过程:
window.onload = function() {setTimeout(function() {// reference to <head>var head = document.getElementsByTagName('head')[0];// a new CSSvar css = document.createElement('link');css.type = "text/css";css.rel= "stylesheet";css.href = https://www.isolves.com/it/cxkf/yy/js/2022-01-04/"http://domain.tld/preload.css";// a new JSvar js= document.createElement("script");js.type = "text/javascript";js.src= "http://domain.tld/preload.js";// preload JS and CSShead.AppendChild(css);head.appendChild(js);// preload imagenew Image().src = "http://domain.tld/preload.png";}, 1000); };这里,我们通过DOM创建三个元素来实现三个文件的预加载 。正如上面提到的那样,使用Ajax,加载文件不会应用到加载页面上 。从这点上看,Ajax方法优越于JavaScript 。
- End -
【3种Javascript图片预加载的方法详解】
推荐阅读
- JavaScript,面向对象,实现继承,对象冒充和原型链继承,代码
- 斯里兰卡乌瓦红茶图片,斯里兰卡红茶历史
- 全职妈妈|让很多人误解的职业
- 贾森·理查德森|盘点NBA5大理查德森
- 泡好的红茶图片大全,黑茶的历史渊源介绍茶文化
- 17 个高频好用的JavaScript 代码块
- 滇红工夫红茶包装图片,红茶的种类和图片大全
- 国外红茶产地,识红茶种类图片
- 红茶哪些种类图片,什么是绿茶有哪些种类
- 如何选购优质红茶,红茶的种类和图片大全
