The preload value of the <link> element's rel attribute allows you to write declarative fetch requests in your HTML <head>, specifying resources that your pages will need very soon after loading, which you therefore want to start preloading early in the lifecycle of a page load, before the browser's main rendering machinery kicks in. This ensures that they are made available earlier and are less likely to block the page's first render, leading to performance improvements. This article provides a basic guide to how preload works.

The basicsSection
You most commonly use the humble <link> element when loading a CSS file to style your page with:

<link rel="stylesheet" href="styles/main.css">
Here however, we will use a rel value of preload, which turns the <link> element into a preloader for pretty much any resource we want. At a basic level, you also need to specify the path to the resource to be preloaded in the href attribute, and the type of resource you are preloading in the as attribute.

A simple example might look like this (see our JS and CSS example source, and also live):

<head>
<meta charset="utf-8">
<title>JS and CSS preload example</title>

<link rel="preload" href="style.css" as="style">
<link rel="preload" href="main.js" as="script">

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

<body>
<h1>Porsche PIWIS Tester III</h1>
<canvas></canvas>

<script src="main.js"></script>
</body>
Here we are preloading our CSS and JavaScript files so they will be available as soon as they are required during the rendering of the page later on. This example is somewhat trivial, but the benefits can be seen much more clearly, the later in the rendering the resources are discovered and the larger they are. For example, what about resources that are pointed to from inside a CSS file like fonts or images, or larger images and video files?

preload has other advantages too. Using as to specify the type of content to be preloaded allows the browser to:

Prioritize resource loading more accurately.
Match future requests, reusing the same resource if appropriate.
Apply the correct content security policy to the resource.
Set the correct Accept request headers for it.
What types of content can be preloaded?Section
Many different content types can be preloaded; the main available as attribute values are as follows:

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.
Note: You can read a bit more detail about these values and the web features they are expected to be consumed by in the Preload spec — see link element extensions. Also note that the full list of values the as attribute can take is governed by the definitions in the Fetch spec — see request destinations.

Including a MIME typeSection
<link> elements can accept a type attribute, which contains the MIME type of the resource the element is pointing to. This is especially useful when preloading resources — the browser will use the type attribute value to work out whether it supports that resource, and will only start downloading it if this is the case, ignoring it if not.

You can see an example of this in our video example (see the full source code, and also the live version):

<head>
<meta charset="utf-8">
<title>LONSDOR K518S Key Programmer</title>

<link rel="preload" href="sintel-short.mp4" as="video" type="video/mp4">
</head>
<body>
<video controls>
<source src="sintel-short.mp4" type="video/mp4">
<source src="sintel-short.webm" type="video/webm">
<p>Your browser doesn't support HTML5 video. Here is a <a href="sintel-short.mp4">link to the video</a> instead.</p>
</video>
</body>
So in this case, browsers that support MP4s will preload and use the MP4, making the video player hopefully smoother/more responsive for users. Browsers that don't support the MP4 can still load the WebM version, but don't get the advantages of preloading. This shows how preloading content can be combined with the philosophy of progressive enhancement.

Cross-origin fetchesSection
If you've got your sites' CORS settings worked out properly, you can successfully preload cross-origin resources as long as you set a crossorigin attribute on your <link> element.

One interesting case in which this applies even if the fetch is not cross-origin is font files. Because of various reasons, these have to be fetched using anonymous mode CORS (see Font fetching requirements if you are interested in all the details).

Let's use this case as an example, firstly because font loading is a really good use case for preloading, and secondly, because it is easier than setting up a cross-origin request example. You can see the full example source code on GitHub (also see it live):

<head>
<meta charset="utf-8">
<title>Web font example</title>

<link rel="preload" href="fonts/cicle_fina-webfont.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="fonts/zantroke-webfont.woff2" as="font" type="font/woff2" crossorigin="anonymous">

<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
...
</body>
You'll see here that not only are we providing the MIME type hints in the type attributes, but we are also providing the crossorigin attribute to handle the CORS issue.

Including mediaSection
One nice feature of <link> elements is their ability to accept media attributes. These can accept media types or full-blown media queries, allowing you to do responsive preloading!

Let's look at a very simple example (see it on GitHub — source code, live example):

<head>
<meta charset="utf-8">
<title>Responsive preload example</title>

<link rel="preload" href="bg-image-narrow.png" as="image" media="(max-width: 600px)">
<link rel="preload" href="bg-image-wide.png" as="image" media="(min-width: 601px)">

<link rel="stylesheet" href="main.css">
</head>
<body>
<header>
<h1>SBB3 PRO3 Key Programmer</h1>

</header>

<script>
var mediaQueryList = window.matchMedia("(max-width: 600px)");
var header = document.querySelector('header');

if(mediaQueryList.matches) {
header.style.backgroundImage = 'url(bg-image-narrow.png)';
} else {
header.style.backgroundImage = 'url(bg-image-wide.png)';
}
</script>
</body>
You'll see that we are including media attributes on our <link> elements so that a narrow image is preloaded if the user is on a narrow screen device, and a wider image is loaded if they are on a wider screen device. We still need to attach the correct image to the header depending on the result — we use Window.matchMedia / MediaQueryList to do this (see Testing media queries for more information on this).

This makes it much more likely that the font will be available by the time the page render is complete, cutting down on FOUT (flash of unstyled text) issues.

Note that this doesn't have to be limited to images, or even files of the same type — think big! You could perhaps preload then display a simple SVG diagram if the user is on a narrow screen where bandwidth and CPU is potentially more limited, or preload a complex chunk of JavaScript then use it to render an interactive 3D model if the user's resources are more plentiful.

Scripting and preloadsSection
Another nice thing about these preloads is that you can execute them completely with script if desired. For example, here we are creating a HTMLLinkElement instance, then attaching it to the DOM:

var preloadLink = document.createElement("link");
preloadLink.href = "myscript.js";
preloadLink.rel = "preload";
preloadLink.as = "script";
document.head.appendChild(preloadLink);
This means that the browser will preload the JavaScript file, but not actually use it yet.

To use it, you could do this when desired:

var preloadedScript = document.createElement("script");
preloadedScript.src = "myscript.js";
document.body.appendChild(preloadedScript);
This is useful when you want to preload a script, but then defer executing it until exactly when you need it.

Other resource preloading mechanismsSection
Other preloading features exist, but none are quite as fit for purpose as <link rel="preload">:

<link rel="prefetch"> has been supported in browsers for a long time, but it is intended for prefetching resources that will be used in the next navigation/page load (e.g. when you go to the next page). This is fine, but isn't useful for the current page! In addition, browsers will give prefetch resources a lower priority than preload ones — the current page is more important than the next one. See Link prefetching FAQ for more details.
<link rel="prerender"> is used to render the specified webpage in the background, speeding up page load if the user navigates to it. Because of the potential to waste users bandwidth, Chrome treats prerender as a NoState prefetch instead.
<link rel="subresource"> was supported in Chrome a while ago, and was intended to tackle preloading resources for the current navigation/page load, but it had a problem — there was no way to work out a priority for fetching the items (as didn't exist back then), so they all ended up being fetched with fairly low priority, which didn't help the situation.
There are a number of script-based resource loaders out there, but they don't have any power over the browser's fetch prioritization queue, and are subject to much the same performance problems.

How to Preloading content with rel preload的更多相关文章

  1. 3 Ways to Preload Images with CSS, JavaScript, or Ajax---reference

    Preloading images is a great way to improve the user experience. When images are preloaded in the br ...

  2. Webpack 4教程 - 第八部分 使用prefetch和preload进行动态加载

    转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者.原文出处:https://wanago.io/2018/08/13/webpack-4-course-part ...

  3. webpack之打包分析以及prefetching和preloading

    打包分析: https://webpack.js.org/guides/code-splitting/#bundle-analysis        性能优化使用缓存是很有限的,现在更多的应该是再编写 ...

  4. prefetch 和 preload 及 webpack 的相关处理

    使用预取和预加载是网站性能和用户体验提升的一个很好的途径,本文介绍了使用 prefetch 和 prefetch 进行预取和预加载的方法,并使用 webpack 进行实现 Link 的链接类型 < ...

  5. 通过link的preload进行内容预加载

    Preload 作为一个新的web标准,旨在提高性能和为web开发人员提供更细粒度的加载控制.Preload使开发者能够自定义资源的加载逻辑,且无需忍受基于脚本的资源加载器带来的性能损失. <l ...

  6. prefetch & preload & prerender & dns-prefetch & preconnect

    prefetch & preload & prerender & dns-prefetch & preconnect performance optimization ...

  7. Preload,Prefetch 和它们在 Chrome 之中的优先级

    前言 上周五到的时候,想起之前在手游平台上有处理dns-prefetch的优化,那这篇分享的就更仔细了.今日早读文章由@gy134340翻译并授权分享. 正文从这开始- 今天我们来深入研究一下 Chr ...

  8. Web 性能优化:Preload与Prefetch的使用及在 Chrome 中的优先级

    摘要: 理解Preload与Prefetch. 原文:Web 性能优化:Preload,Prefetch的使用及在 Chrome 中的优先级 作者:前端小智 Fundebug经授权转载,版权归原作者所 ...

  9. 资源预加载preload和资源预读取prefetch简明学习

    前面的话 基于VUE的前端小站改造成SSR服务器端渲染后,HTML文档会自动使用preload和prefetch来预加载所需资源,本文将详细介绍preload和prefetch的使用 资源优先级 在介 ...

随机推荐

  1. 使用 Sonar 检测代码质量

    经历了一段时间的加班赶项目进度之后,今天终于闲下来了.忽然不知道干啥.于是,想着做点什么吧.突然想起了码云上面有个代码分析的功能,用的是 Sonar 于是想来玩玩这个. 一.下载Sonar,和初始化, ...

  2. jquery源码解析日常

    介绍:JQuery是继prototype之后又一个优秀的Javascript库.它是轻量级的js库 ,它兼容CSS3,还兼容各种浏览器(IE 6.0+, FF1.5+, Safari 2.0+, Op ...

  3. Hexo主题yilia增加gitalk评论插件

    虽然gitment可以实现评论功能,但是适配方面做的并不好,这里借用GitHub上的gitalk项目用来优化个人博客的评论功能 下面记录自己从gitment到gitalk的替换过程: 1.在layou ...

  4. nginx 错误502 upstream sent too big header while reading response header from upstream

    查看nginx的错误日志,得到以下错误信息:upstream sent too big header while reading response header from upstream按字面意思理 ...

  5. 【Linux】-- 在linux上安装mysql及基本操作

    1.MySQL的安装 1.删除mariadb数据库 yum remove mariadb-libs.x86_64 CentOS7默认安装mariadb数据库,所以要先删除 2.下载mysql源 进入m ...

  6. OI/ACM 刷题网站 人气OJ简介

         SPOJ简介 SPOJ是波兰最为出色的Online Judge之一,界面和谐,题目类型也非常丰富,适合有一定基础的选手练习,对高手而言也是个提高能力的良好平台. SPOJ题目分类:class ...

  7. java线程系列之三(线程协作)

    本文来自:高爽|Coder,原文地址:http://blog.csdn.net/ghsau/article/details/7433673,转载请注明. 上一篇讲述了线程的互斥(同步),但是在很多情况 ...

  8. Java当中的异常2

    1.throw的作用 如果一行有可能代码抛出Execption对象或者check exception 就必须对这行代码进行处理 2.throws的作用 Throws表明这个类或者方法可能会产生一个指定 ...

  9. ECMA Script 6_解构赋值_模式匹配

    解构赋值 从数组中提取值,按照对应位置,对变量赋值 只要等号右边的值不是对象或数组,就先将其转为对象. 由于 undefined 和 null 无法转为对象,所以对它们进行解构赋值,都会报错 let ...

  10. Solve Error: "errcode": 40016, "errmsg": "invalid button size hint"

    在使用微信官方给的添加自定义菜单的示例代码: { "button": [ { "name": "扫码", "sub_button& ...