0
0
HtmlHow-ToBeginner · 4 min read

How to Prefetch in HTML: Syntax and Examples

To prefetch resources in HTML, use the <link rel="prefetch" href="URL" as="type"> tag inside the <head>. This tells the browser to fetch the resource in advance, improving load speed when it is needed later.
📐

Syntax

The <link> tag with rel="prefetch" tells the browser to fetch a resource early. The href attribute specifies the URL of the resource to prefetch.

  • rel="prefetch": Indicates the resource should be fetched ahead of time.
  • href: URL of the resource to prefetch (e.g., script, image, stylesheet).
  • as (optional): Specifies the type of resource (like script, image, style) to help browser prioritize.
html
<link rel="prefetch" href="/path/to/resource.js" as="script">
💻

Example

This example prefetches a JavaScript file so it loads faster when used later in the page.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Prefetch Example</title>
  <link rel="prefetch" href="/scripts/app.js" as="script">
</head>
<body>
  <h1>Prefetch Demo</h1>
  <p>The script <code>app.js</code> is prefetched in the background.</p>
  <script src="/scripts/app.js"></script>
</body>
</html>
Output
A simple webpage with a heading 'Prefetch Demo' and a paragraph explaining the script is prefetched.
⚠️

Common Pitfalls

  • Not specifying as can reduce prefetch effectiveness because the browser can't prioritize the resource type.
  • Prefetching too many resources wastes bandwidth and can slow down the page.
  • Using rel="preload" instead of prefetch when the resource is needed immediately can cause delays.
  • Prefetching resources that are never used wastes data and memory.
html
<!-- Wrong: missing 'as' attribute -->
<link rel="prefetch" href="/styles/main.css">

<!-- Right: with 'as' attribute -->
<link rel="prefetch" href="/styles/main.css" as="style">
📊

Quick Reference

Use <link rel="prefetch" href="URL" as="type"> to hint the browser to fetch resources early for future use. Limit prefetching to important resources to save bandwidth.

AttributeDescriptionExample
relRelationship type, must be 'prefetch'rel="prefetch"
hrefURL of the resource to prefetchhref="/image.jpg"
asType of resource to help browser prioritizeas="image"

Key Takeaways

Use to load resources early for better performance.
Always specify the 'as' attribute to help the browser prioritize the resource.
Avoid prefetching too many or unused resources to save bandwidth.
Prefetch is for resources needed soon but not immediately.
Test prefetching impact using browser DevTools network panel.