preload & prefetch

原文地址在 我的笔记里,觉得还行就给个 star 吧:)

关于 preloadprefetch 早有耳闻,知道它们可以优化页面加载速度,然具体情况却了解不多。搜索了相关的资料后对其有了些认识,在此记录一下。

preload

通常在页面中,我们需要加载一些脚本和样式,而使用 preload 可以对当前页面所需的脚本、样式等资源进行预加载,而无需等到解析到 scriptlink 标签时才进行加载。这一机制使得资源可以更早的得到加载并可用,且更不易阻塞页面的初步渲染,进而提升性能。

使用方式

link 标签的 rel 属性的值设为 preloadas 属性的值为资源类型(如脚本为 script,样式表为 style

<head>
  <meta charset="utf-8">
  <title>preload example</title>
  <!-- 对 style.css 和 index.js 进行预加载 -->
  <link rel="preload" href="style.css" as="style">
  <link rel="preload" href="index.js" as="script">

  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div id="app"></div>

  <script src="index.js"></script>
</body>

prefetch

preload 一样,都是对资源进行预加载,但是 prefetch 加载的资源一般不是用于当前页面的,即未来很可能用到的这样一些资源,简单点说就是其他页面会用到的资源。当然,prefetch 不会像 preload 一样,在页面渲染的时候加载资源,而是利用浏览器空闲时间来下载。当进入下一页面,就可直接从 disk cache 里面取,既不影响当前页面的渲染,又提高了其他页面加载渲染的速度。

使用方式

preload 很相似,无需指定 as 属性:

<head>
  <meta charset="utf-8">
  <title>preload example</title>
  <!-- 对 style.css 和 index.js 进行 preload 预加载 -->
  <link rel="preload" href="style.css" as="style">
  <link rel="preload" href="index.js" as="script">

  <!-- 对资源进行 prefetch 预加载 -->
  <link rel="prefetch" href="next.css">
  <link rel="prefetch" href="next.js">

  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div id="app"></div>

  <script src="index.js"></script>
</body>

总结

对当前页面需要的资源,使用 preload 进行预加载,对其它页面需要的资源进行 prefetch 预加载。

猜你喜欢

转载自www.cnblogs.com/baimeishaoxia/p/11817078.html
今日推荐