1. 纯CSS:
1
2
3
4
5
6
7
8
9
|
#preload
-01
{
}
#preload
-02
{
}
#preload
-03
{
}
|
2. JS+CSS优化:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
// better image preloading @ http://perishablepress.com/press/2009/12/28/3-ways-preload-images-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);
|
3. JS代码1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<div class=
"hidden"
>
<script type=
"text/javascript"
>
<!--
//--><![CDATA[//><!--
var
images =
new
Array()
function
preload() {
for
(i = 0; i < preload.arguments.length; i++) {
images[i] =
new
Image()
images[i].src = preload.arguments[i]
}
}
preload(
)
//--><!]]>
</script>
</div>
|
4. JS代码2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<div class=
"hidden"
>
<script type=
"text/javascript"
>
<!--
//--><![CDATA[//><!--
if
(document.images) {
img1 =
new
Image();
img2 =
new
Image();
img3 =
new
Image();
}
//--><!]]>
</script>
</div>
|
5. JS代码优化2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
function
preloader() {
if
(document.images) {
var
img1 =
new
Image();
var
img2 =
new
Image();
var
img3 =
new
Image();
}
}
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);
|
6. Ajax代码1:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
window.onload =
function
() {
setTimeout(
function
() {
// XHR to request a JS and a CSS
var
xhr =
new
XMLHttpRequest();
xhr.send(
''
);
xhr =
new
XMLHttpRequest();
xhr.send(
''
);
// preload image
}, 1000);
};
|
7. Ajax代码2:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
window.onload =
function
() {
setTimeout(
function
() {
// reference to <head>
var
head = document.getElementsByTagName(
'head'
)[0];
// a new CSS
var
css = document.createElement(
'link'
);
css.type =
"text/css"
;
css.rel =
"stylesheet"
;
// a new JS
var
js = document.createElement(
"script"
);
js.type =
"text/javascript"
;
// preload JS and CSS
head.appendChild(css);
head.appendChild(js);
// preload image
}, 1000);
};
|
源引:http://www.jb51.net/article/67850.htm