preload value of the <link> 元素的 rel attribute lets you declare fetch requests in the HTML's <head> , specifying resources that your page will need very soon, which you want to start loading early in the page lifecycle, before browsers' main rendering machinery kicks in. This ensures they are available earlier and are less likely to block the page's render, improving performance.

This article provides a basic guide to how <link rel="preload"> works.

基础

You most commonly use <link> to load 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 <link> into a preloader for any resource we want. You will also need to specify:

  • The path to the resource in the href 属性。
  • The type of resource in the as 属性。

A simple example might look like this (see our JS and CSS example source ,和 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>bouncing balls</h1>
  <canvas></canvas>
  <script src="main.js" defer></script>
</body>

Here we preload our CSS and JavaScript files so they will be available as soon as they are required for the rendering of the page later on. This example is trivial, as the browser probably discovers the <link rel="stylesheet"> and <script> elements in the same chunk of HTML as the preloads, but the benefits can be seen much more clearly the later resources are discovered and the larger they are. For example:

  • Resources that are pointed to from inside CSS, like fonts or images.
  • Resources that JavaScript can request, like JSON, imported scripts, or web workers.
  • 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.
  • Store in the cache for future requests, reusing the 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?

Many different content types can be preloaded. The possible as attribute values are:

  • audio : Audio file, as typically used in <audio> .
  • document : An HTML document intended to be embedded by a <frame> or <iframe> .
  • embed : A resource to be embedded inside an <embed> 元素。
  • fetch : Resource to be accessed by a fetch or XHR request, such as an ArrayBuffer or JSON file.
  • font : Font file.
  • image : Image file.
  • 对象 : A resource to be embedded inside an <object> 元素。
  • script : JavaScript file.
  • style : CSS stylesheet.
  • track : WebVTT file.
  • worker : A JavaScript web worker or shared worker.
  • 视频 : Video file, as typically used in <video> .

注意 : 视频 preloading is included in the Preload spec, but is not currently implemented by browsers.

注意 : There's more detail about these values and the web features they expect 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 Fetch spec — see request destinations .

Including a MIME type

<link> elements can accept a type attribute, which contains the MIME type of the resource the element points to. This is especially useful when preloading resources — the browser will use the type attribute value to work out if it supports that resource, and will only download it if so, 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>Video preload example</title>
  <link rel="preload" href="sintel-short.mp4" as="video" type="video/mp4">
  <link rel="preload" href="sintel-short.webm" as="video" type="video/webm">
</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 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.

CORS-enabled fetches

When preloading resources that are fetched with CORS enabled (e.g. fetch() , XMLHttpRequest or fonts ), special care needs to be taken to setting the crossorigin attribute on your <link> element. The attribute needs to be set to match the resource's CORS and credentials mode, event when the fetch is not cross-origin.

As mentioned above, one interesting case where this applies is font files. Because of various reasons, these have to be fetched using anonymous mode CORS (see Font fetching requirements ).

Let's use this case as an 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>
  <link rel="preload" href="fonts/zantroke-webfont.woff2" as="font" type="font/woff2" crossorigin>
  <link href="style.css" rel="stylesheet">
</head>
<body>
  …
</body>

Not only are we providing the MIME type hints in the type attributes, but we are also providing the crossorigin attribute to make sure the preload's CORS mode matches the eventual font resource request.

Including media

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 an example (see it on GitHub — 源代码 , 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>My site</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>

We include media attributes on our <link> elements so that a narrow image is preloaded if the user has a narrow viewport, and a wider image is loaded if they have a wide viewport. We use Window.matchMedia / MediaQueryList to do this (see Testing media queries for more).

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

This doesn't have to be limited to images, or even files of the same type — think big! You could perhaps preload and 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 preloads

Another nice thing about these preloads is that you can execute them with script. For example, here we create a HTMLLinkElement instance, then attach 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 myscript.js file, but not actually use it yet. To use it, you could do this:

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 execution until exactly when you need it.

Other resource preloading mechanisms

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. See Link prefetching FAQ 了解更多细节。
  • <link rel="prerender"> renders a specified webpage in the background, speeding up its load if the user navigates to it. Because of the potential to waste users bandwidth, Chrome treats prerender 作为 NoState prefetch 代替。
  • <link rel="subresource"> was supported in Chrome a while ago, and was intended to tackle the same issue as preload , but it had a problem: there was no way to work out a priority for the items ( as didn't exist back then), so they all got fetched with fairly low priority.
  • 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.

规范

规范 状态 注释
Preload
The definition of 'preload' in that specification.
候选推荐 Further details of preload .
HTML 实时标准
The definition of 'rel=preload' in that specification.
实时标准 Definition of rel=preload .

浏览器兼容性

更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
preload 实验性 Chrome 完整支持 50 Edge 完整支持 ≤79 Firefox 不支持 56 — 57 注意事项
不支持 56 — 57 注意事项
注意事项 Disabled due to various web compatibility issues (e.g. bug 1405761 ).
IE ? Opera 完整支持 37 Safari ? WebView Android 完整支持 50 Chrome Android 完整支持 50 Firefox Android 不支持 56 — 57 注意事项
不支持 56 — 57 注意事项
注意事项 Disabled due to various web compatibility issues (e.g. bug 1405761 ).
Opera Android ? Safari iOS ? Samsung Internet Android 完整支持 5.0

图例

完整支持

完整支持

不支持

不支持

兼容性未知 ?

兼容性未知

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

见实现注意事项。

见实现注意事项。

另请参阅

元数据

  • 最后修改:
  1. Allowing cross-origin use of images and canvas
  2. 使用 CSS 将颜色应用到 HTML 元素
  3. Block-level elements
  4. 用于 HTML 的日期和时间格式
  5. 全局属性
    1. 全局属性
    2. accesskey
    3. autocapitalize
    4. class
    5. contenteditable
    6. contextmenu
    7. data-*
    8. dir
    9. draggable
    10. dropzone
    11. hidden
    12. id
    13. inputmode
    14. is
    15. itemid
    16. itemprop
    17. itemref
    18. itemscope
    19. itemtype
    20. lang
    21. part
    22. slot
    23. spellcheck
    24. style
    25. tabindex
    26. title
    27. translate
    28. x-ms-acceleratorkey
    29. x-ms-format-detection
  6. HTML 属性参考
    1. HTML 属性参考
    2. HTML attribute: accept
    3. HTML attribute: capture
    4. HTML attribute: crossorigin
    5. HTML attribute: max
    6. HTML attribute: maxlength
    7. HTML attribute: min
    8. HTML attribute: minlength
    9. HTML attribute: multiple
    10. HTML attribute: pattern
    11. HTML attribute: readonly
    12. HTML attribute: rel
    13. HTML attribute: required
    14. HTML attribute: size
    15. HTML attribute: step
    16. The HTML autocomplete attribute
    17. 被禁用
  7. HTML documentation index
  8. HTML 元素参考
    1. HTML 元素参考
    2. <a>: The Anchor element
    3. <abbr>: The Abbreviation element
    4. <acronym>
    5. <address>: The Contact Address element
    6. <applet>: The Embed Java Applet element
    7. <area>
    8. <article>: The Article Contents element
    9. <aside>: The Aside element
    10. <audio>: The Embed Audio element
    11. <b>: The Bring Attention To element
    12. <base>: The Document Base URL element
    13. <basefont>
    14. <bdi>: The Bidirectional Isolate element
    15. <bdo>: The Bidirectional Text Override element
    16. <bgsound>: The Background Sound element (obsolete)
    17. <big>: The Bigger Text element
    18. <blink>: The Blinking Text element (obsolete)
    19. <blockquote>: The Block Quotation element
    20. <body>: The Document Body element
    21. <br>: The Line Break element
    22. <button>: The Button element
    23. <canvas>: The Graphics Canvas element
    24. <caption>: The Table Caption element
    25. <center>: The Centered Text element (obsolete)
    26. <cite>: The Citation element
    27. <code>: The Inline Code element
    28. <col>
    29. <colgroup>
    30. <command>: The HTML Command element
    31. <content>: The Shadow DOM Content Placeholder element (obsolete)
    32. <data>
    33. <datalist>: The HTML Data List element
    34. <dd>: The Description Details element
    35. <del>: The Deleted Text element
    36. <details>: The Details disclosure element
    37. <dfn>: The Definition element
    38. <dialog>: The Dialog element
    39. <dir>: The Directory element (obsolete)
    40. <div>: The Content Division element
    41. <dl>: The Description List element
    42. <dt>: The Description Term element
    43. <element>: The Custom Element element (Obsolete)
    44. <em>: The Emphasis element
    45. <embed>: The Embed External Content element
    46. <fieldset>: The Field Set element
    47. <figcaption>: The Figure Caption element
    48. <figure>: The Figure with Optional Caption element
    49. <font>
    50. <footer>
    51. <form>
    52. <frame>
    53. <frameset>
    54. <h1>–<h6>: The HTML Section Heading elements
    55. <head>: The Document Metadata (Header) element
    56. <header>
    57. <hgroup>
    58. <hr>: The Thematic Break (Horizontal Rule) element
    59. <html>: The HTML Document / Root element
    60. <i>: The Idiomatic Text element
    61. <iframe>: The Inline Frame element
    62. <image>: The obsolete Image element
    63. <img>: The Image Embed element
    64. <input>: The Input (Form Input) element
    65. <ins>
    66. <isindex>
    67. <kbd>: The Keyboard Input element
    68. <keygen>
    69. <label>
    70. <legend>
    71. <li>
    72. <link>: The External Resource Link element
    73. <listing>
    74. <main>
    75. <map>
    76. <mark>: The Mark Text element
    77. <marquee>: The Marquee element (Obsolete)
    78. <menu>
    79. <menuitem>
    80. <meta>: The Document-level Metadata element
    81. <meter>: The HTML Meter element
    82. <multicol>: The HTML Multi-Column Layout element (Obsolete)
    83. <nav>: The Navigation Section element
    84. <nextid>: The NeXT ID element (Obsolete)
    85. <nobr>: The Non-Breaking Text element (obsolete)
    86. <noembed>: The Embed Fallback element (Obsolete)
    87. <noframes>: The Frame Fallback element
    88. <noscript>
    89. <object>
    90. <ol>: The Ordered List element
    91. <optgroup>
    92. <option>: The HTML Option element
    93. <output>: The Output element
    94. <p>: The Paragraph element
    95. <param>: The Object Parameter element
    96. <picture>: The Picture element
    97. <plaintext>: The Plain Text element (Deprecated)
    98. <pre>: The Preformatted Text element
    99. <progress>: The Progress Indicator element
    100. <q>: The Inline Quotation element
    101. <rb>: The Ruby Base element
    102. <rp>: The Ruby Fallback Parenthesis element
    103. <rt>: The Ruby Text element
    104. <rtc>: The Ruby Text Container element
    105. <ruby>
    106. <s>
    107. <samp>: The Sample Output element
    108. <script>: The Script element
    109. <section>: The Generic Section element
    110. <select>: The HTML Select element
    111. <shadow>: The obsolete Shadow Root element
    112. <slot>
    113. <small>: the side comment element
    114. <source>: The Media or Image Source element
    115. <spacer>
    116. <span>
    117. <strike>
    118. <strong>: The Strong Importance element
    119. <style>: The Style Information element
    120. <sub>: The Subscript element
    121. <summary>: The Disclosure Summary element
    122. <sup>: The Superscript element
    123. <table>: The Table element
    124. <tbody>: The Table Body element
    125. <td>: The Table Data Cell element
    126. <template>: The Content Template element
    127. <textarea>
    128. <tfoot>: The Table Foot element
    129. <th>
    130. <thead>: The Table Head element
    131. <time>
    132. <title>: The Document Title element
    133. <tr>: The Table Row element
    134. <track>: The Embed Text Track element
    135. <tt>: The Teletype Text element (obsolete)
    136. <u>: The Unarticulated Annotation (Underline) element
    137. <ul>: The Unordered List element
    138. <var>: The Variable element
    139. <video>: The Video Embed element
    140. <wbr>
    141. <xmp>
  9. HTML 参考
  10. 内联元素
  11. Link 类型
    1. Link 类型
    2. Link types: dns-prefetch
    3. Link types: manifest
    4. Link types: modulepreload
    5. Link types: noopener
    6. Link types: noreferrer
    7. Link types: preconnect
    8. Link types: prefetch
    9. Link types: preload
    10. Link types: prerender
  12. Microdata
  13. Microformats
  14. 采用 rel="preload" 预加载内容
  15. Quirks Mode and Standards Mode
  16. Using the application cache

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1