如何实现HTML5的预加载

html-css010

如何实现HTML5的预加载,第1张

<!-- 页面,可以使用绝对或者相对路径 --> 

<link rel="prefetch" href="page2.html" /> 

<!-- 图片,也可以是其他类型的文件 --> 

<link rel="prefetch" href="sprite.png" />

从上面的HTML代码可以看出,预加载使用 <link>标签,并指定 rel="prefetch" 属性,而href属性就是需要预加载的文件路径。而Mozilla还实现了一些类似的 link rel 属性:

<link rel="prefetch alternate stylesheet" title="Designed for Mozilla" href="mozspecific.css" /> 

<link rel="next" href="2.html" />

备注: https 协议也同样支持。

何时需要预加载 

网站是否采用预加载取决于你的需求,下面是一些建议: 

- 如果一系列的页面幻灯片一样展示,那么可以预加载前后各1至3个页面. 

- 加载网站内部通用的图片 

- 在搜索结果页预加载下一页

阻止预加载 

Firefox 允许禁止预加载模式,代码如下: 

user_pref("network.prefetch-next", false)

我用css3写了个demo

<html>

<head>

<meta charset="utf-8"/>

<title>Loading</title>

<style>

.spinner {

margin: 100px auto

width: 60px

height: 60px

text-align: center

font-size: 10px

}

.spinner >div {

background-color: #67CF22

height: 100%

width: 6px

display: inline-block

-webkit-animation: stretchdelay 1.2s infinite ease-in-out

animation: stretchdelay 1.2s infinite ease-in-out

}

.spinner .rect2 {

-webkit-animation-delay: -1.1s

animation-delay: -1.1s

}

.spinner .rect3 {

-webkit-animation-delay: -1.0s

animation-delay: -1.0s

}

.spinner .rect4 {

-webkit-animation-delay: -0.9s

animation-delay: -0.9s

}

.spinner .rect5 {

-webkit-animation-delay: -0.8s

animation-delay: -0.8s

}

@-webkit-keyframes stretchdelay {

0%, 40%, 100% { -webkit-transform: scaleY(0.4) }

20% { -webkit-transform: scaleY(1.0) }

}

@keyframes stretchdelay {

0%, 40%, 100% {

transform: scaleY(0.4)

-webkit-transform: scaleY(0.4)

} 20% {

transform: scaleY(1.0)

-webkit-transform: scaleY(1.0)

}

}

</style>

</head>

<body>

<div class="spinner">

<div class="rect1"></div>

<div class="rect2"></div>

<div class="rect3"></div>

<div class="rect4"></div>

<div class="rect5"></div>

</div>

</body>

</html>

你这个情况和XMLHttpRequest完全无关。 性能影响最大的是操作DOM, 你一次性往DOM里面加载了几MB的数据, 我很难想象DOM得假死成什么样子。

你这个情况要么服务器按页返回数据, 一页几十条这样。 要么使用setTimeout 按 200毫秒分批次把数据插入到DOM里面。