在该脚本的第一部分,我们获取使用类选择器的元素,并为其设置了background属性,以预加载不同的图片。
该脚本的第二部分,我们使用addLoadEvent()函数来延迟preloader()函数的加载时间,直到页面加载完毕。
如果JavaScript无法在用户的浏览器中正常运行,会发生什么?很简单,图片不会被预加载,当页面调用图片时,正常显示即可。
[b]方法二:仅使用JavaScript实现预加载 [/b]
上述方法有时确实很高效,但我们逐渐发现它在实际实现过程中会耗费太多时间。相反,我更喜欢使用纯JavaScript来实现图片的预加载。下面将提供两种这样的预加载方法,它们可以很漂亮地工作于所有现代浏览器之上。
JavaScript代码段1
只需简单编辑、加载所需要图片的路径与名称即可,很容易实现:
[url=http://domain.tld/gallery/image-001.jpg]http://domain.tld/gallery/image-001.jpg[/url]",
"[url=http://domain.tld/gallery/image-002.jpg]http://domain.tld/gallery/image-002.jpg[/url]",
"[url=http://domain.tld/gallery/image-003.jpg]http://domain.tld/gallery/image-003.jpg[/url]"
)
//--><!]]> </script>
</div>
该方法尤其适用预加载大量的图片。我的画廊网站使用该技术,预加载图片数量达50多张。将该脚本应用到登录页面,只要用户输入登录帐号,大部分画廊图片将被预加载。
JavaScript代码段2
该方法与上面的方法类似,也可以预加载任意数量的图片。将下面的脚本添加入任何Web页中,根据程序指令进行编辑即可。
[url=http://domain.tld/path/to/image-001.gif]http://domain.tld/path/to/image-001.gif[/url]";
img2.src = "[url=http://domain.tld/path/to/image-002.gif]http://domain.tld/path/to/image-002.gif[/url]";
img3.src = "[url=http://domain.tld/path/to/image-003.gif]http://domain.tld/path/to/image-003.gif[/url]";
}
//--><!]]> </script>
</div>
正如所看见,每加载一个图片都需要创建一个变量,如“img1 = new Image();”,及图片源地址声明,如“img3.src =
"../path/to/image-003.gif";”。参考该模式,你可根据需要加载任意多的图片。
我们又对该方法进行了改进。将该脚本封装入一个函数中,并使用 addLoadEvent(),延迟预加载时间,直到页面加载完毕。
[url=http://domain.tld/path/to/image-001.gif]http://domain.tld/path/to/image-001.gif[/url]";
img2.src = "[url=http://domain.tld/path/to/image-002.gif]http://domain.tld/path/to/image-002.gif[/url]";
img3.src = "[url=http://domain.tld/path/to/image-003.gif]http://domain.tld/path/to/image-003.gif[/url]";
}
}
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);
[b]方法三:使用Ajax实现预加载[/b]
上面所给出的方法似乎不够酷,那现在来看一个使用Ajax实现图片预加载的方法。该方法利用DOM,不仅仅预加载图片,还会预加载CSS、JavaScript等相关的东西。使用Ajax,比直接使用JavaScript,优越之处在于JavaScript和CSS的加载不会影响到当前页面。该方法简洁、高效。
[url=http://domain.tld/preload.png]http://domain.tld/preload.png[/url]";
}, 1000);
};
上面代码预加载了“preload.js”、“preload.css”和“preload.png”。1000毫秒的超时是为了防止脚本挂起,而导致正常页面出现功能问题。
下面,我们看看如何用JavaScript来实现该加载过程:
[url=http://domain.tld/preload.css]http://domain.tld/preload.css[/url]";
// a new JS
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "[url=http://domain.tld/preload.js]http://domain.tld/preload.js[/url]";
// preload JS and CSS head.appendChild(css);
head.appendChild(js);
// preload image
new Image().src = "[url=http://domain.tld/preload.png]http://domain.tld/preload.png[/url]";
}, 1000);
};
这里,我们通过DOM创建三个元素来实现三个文件的预加载。正如上面提到的那样,使用Ajax,加载文件不会应用到加载页面上。从这点上看,Ajax方法优越于JavaScript。
好了,本文就先介绍到这里,三种实现图片预加载技术的方法大家都已经了解了吧,具体哪个更高效,我想小伙伴们也都看出来了,那就应用到自己的项目中吧。