本文实例汇总了js预加载图片方法。分享给大家供大家参考。具体分析如下:
1. 纯CSS:
@H_301_5@
2. JS+CSS优化:
css-javascript-ajax/
function preloader() {
if (document.getElementById) {
document.getElementById("preload-01").style.background = "url(http://domain.tld/image-01.png) no-repeat -9999px -9999px";
document.getElementById("preload-02").style.background = "url(http://domain.tld/image-02.png) no-repeat -9999px -9999px";
document.getElementById("preload-03").style.background = "url(http://domain.tld/image-03.png) no-repeat -9999px -9999px";
}
}
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);
@H_301_5@
3. JS代码1:
@H_301_5@
@H_301_5@
4. JS代码2:
@H_301_5@
@H_301_5@
5. JS代码优化2:
@H_301_5@
6. Ajax代码1:
@H_301_5@
7. Ajax代码2:
var head = document.getElementsByTagName('head')[0];
// a new CSS
var css = document.createElement('link');
css.type = "text/css";
css.rel = "stylesheet";
css.href = "http://domain.tld/preload.css";
// a new JS
var js = document.createElement("script");
js.type = "text/javascript";
js.src = "http://domain.tld/preload.js";
// preload JS and CSS
head.appendChild(css);
head.appendChild(js);
// preload image
new Image().src = "http://domain.tld/preload.png";
},1000);
};
@H_301_5@
希望本文所述对大家的javascript程序设计有所帮助。