前端性能优化之资源预加载与预加载

html5中的link 标签 包含了几个属性,其中prefetch(空闲时加载)和preload(优先加载)可以让我们在加载资源时提高用户体验。

这里我用css样式进行举例,index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./css/index.css">
    <link rel="prefetch" as="style" href="./css/other.css">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

在加载index.html的样式时,我在引入index.css后加了下边一句代码

<link rel="prefetch" as="style" href="./css/other.css">
其意思为在空闲时加载other.css这一个文件,此时浏览器中资源加载顺序如下:
在加载了index.css后去加载了other.css 且other.css的优先级为最低Lowest。
 
 
other.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./css/other.css">
    <link rel="preload" as="style" href="./css/index.css">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

 

在加载other.html样式时,我在引入other.css后加了下边一句代码

<link rel="preload" as="style" href="./css/index.css">
其意思为优先加载index.css这一个文件,此时浏览器中资源加载顺序如下:
可以看到浏览器优先加载了index.css这一文件且other.css文件其并未显示Size,原因在于已经在index.html中加载并缓存了other.css这个一样式,其详细信息:
总结:我们可以通过在首页添加prefetch让浏览器在空闲时预加载其他页面的资源,这样在打开其他页面时就节省了加载时间,而使用preload能够让我们优先加载一些重要的资源,让用户能够优先看到重要的内容,提高用户体验。
注:在使用时要添加as这一属性声明资源类型其值如下
  • audio: Audio file.
  • document: An HTML document intended to be embedded inside a <frame> or <iframe>.
  • embed: A resource to be embedded inside an <embed> element.
  • fetch: Resource to be accessed by a fetch or XHR request, such as an ArrayBuffer or JSON file.
  • font: Font file.
  • image: Image file.
  • object: A resource to be embedded inside an <embed> element.
  • script: JavaScript file.
  • style: Stylesheet.
  • track: WebVTT file.
  • worker: A JavaScript web worker or shared worker.
  • video: Video file.

 

posted @ 2020-12-04 16:59  那时年少青衫薄。  阅读(1490)  评论(0编辑  收藏  举报