Prefetch & Preload — Predictively Load Resources in Cloudflare
In this tutorial, you'll learn about Prefetch & Preload. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Cloudflare prefetch and preload directives instruct browsers to fetch resources before the user navigates to a page or before the parser encounters the resource, eliminating network latency from critical paths.
What You'll Learn
By the end of this tutorial, you will understand the difference between prefetch, preload, and prerender, how to configure Cloudflare's edge to inject these hints, and how to measure the speed improvement for subsequent page loads.
Why It Matters
Network latency is the largest factor in page load time. Predictively fetching resources while the user reads the current page eliminates that latency entirely. Cloudflare can inject prefetch hints at the edge without modifying application code.
Real-World Use
Doda Browser preloads the URL in the address bar before the user presses Enter. The same principle applies to websites: prefetching likely next pages makes navigation feel instant.
Your Learning Path
flowchart LR
A[Signed Exchanges] --> B[Prefetch & Preload]
B --> C[Page Rules Intro]
C --> D[Page Rules Caching]
D --> E[Page Rules URL Forwarding]
B --> F{You Are Here}
style F fill:#f90,color:#fff
Resource Hints Overview
| Hint | Directive | Behavior |
|---|---|---|
| Preload | <link rel="preload"> |
Fetches resource for the current page, highest priority |
| Prefetch | <link rel="prefetch"> |
Fetches resource for a future navigation, lowest priority |
| Prerender | <link rel="prerender"> |
Entirely renders a page in the background |
| Preconnect | <link rel="preconnect"> |
Opens a connection to an origin in advance |
| DNS-Prefetch | <link rel="dns-prefetch"> |
Resolves DNS for an origin |
When to Use Each
flowchart TD A[Is the resource needed now?] -->|Yes| B[Preload] A -->|No| C[Is it for the next page?] C -->|Yes| D[Prefetch] C -->|No| E[Will the user visit soon?] E -->|Likely| F[Prerender] E -->|Maybe| G[Preconnect or DNS-Prefetch] style B fill:#f90,color:#fff
Enabling Cloudflare Prefetch
Cloudflare's Prefetch feature uses the cf-prefetch header or the Cloudflare Worker to inject prefetch hints into responses.
- Log in to the Cloudflare dashboard.
- Select your domain.
- Go to Speed > Optimization > Prefetch.
- Toggle Prefetch URLs to On.
- Add URL patterns that Cloudflare should prefetch after page load.
Manual Prefetch with Link Headers
# Cloudflare respects these Link headers from your origin
Link: </next-page>; rel=prefetch
Link: </style.css>; rel=preload; as=style
Link: <https://fonts.googleapis.com>; rel=preconnect
Code Examples
Preloading Critical CSS
<!DOCTYPE html>
<html>
<head>
<!-- Preload the most important CSS for above-the-fold content -->
<link rel="preload" href="/critical.css" as="style" />
<link rel="stylesheet" href="/critical.css" />
<!-- Prefetch the next page's hero image -->
<link rel="prefetch" href="/products/headphones/hero.webp" />
<!-- Preconnect to third-party font server -->
<link rel="preconnect" href="https://fonts.googleapis.com" crossorigin />
</head>
<body>
<h1>Product Catalog</h1>
<a href="/products/headphones">View Headphones</a>
<!-- The hero image for the headphones page starts prefetching now -->
</body>
</html>
JavaScript API for Dynamic Prefetch
// Dynamically prefetch resources based on user behavior
const prefetchLinks = document.querySelectorAll('a[data-prefetch]');
prefetchLinks.forEach(link => {
link.addEventListener('mouseenter', () => {
const url = link.getAttribute('href');
const prefetchLink = document.createElement('link');
prefetchLink.rel = 'prefetch';
prefetchLink.href = url;
document.head.appendChild(prefetchLink);
console.log('Prefetching:', url);
});
});
// Expected behavior:
// Hovering over a link triggers a prefetch request
// If the user clicks the link within 30 seconds, the page loads instantly
Cloudflare Worker Injecting Prefetch Hints
// Cloudflare Worker that automatically adds prefetch hints
export default {
async fetch(request, env) {
const response = await fetch(request);
if (response.headers.get('Content-Type')?.includes('text/html')) {
const url = new URL(request.url);
const prefetchUrls = getLikelyNextPages(url.pathname);
const newHeaders = new Headers(response.headers);
prefetchUrls.forEach(target => {
newHeaders.append('Link', `<${target}>; rel=prefetch`);
});
return new Response(response.body, {
status: response.status,
headers: newHeaders,
});
}
return response;
}
};
function getLikelyNextPages(currentPath) {
const navigationMap = {
'/': ['/products', '/about'],
'/products': ['/products/detail'],
};
return navigationMap[currentPath] || [];
}
Common Errors
Prefetch wastes bandwidth on mobile. Prefetch consumes data even if the user never visits the target page. On metered connections, use data-saver media queries or disable prefetch for mobile users.
Preload blocks CSS rendering. If a preloaded CSS file does not have a matching stylesheet link in the HTML, the browser may queue the preload unnecessarily. Always pair rel="preload" with rel="stylesheet" for CSS.
Prerender causes high memory usage. Prerendering a full page creates a complete DOM tree in the background. Limit prerender to the single most likely next page to avoid memory pressure.
Prefetch from different origins. Cross-origin prefetch requires the target origin to set appropriate CORS headers. Without Access-Control-Allow-Origin, the prefetch is silently dropped.
DNS-Prefetch ignored on HTTPS pages. Modern browsers limit DNS prefetching on HTTPS to prevent privacy leaks. Use Preconnect instead for origins where you need a full TCP + TLS handshake.
Practice Questions
- What is the difference between prefetch and preload in terms of priority and use case?
- Why might you use preconnect instead of DNS-prefetch for a third-party API origin?
- How can Cloudflare Workers help automate prefetch hint injection?
Challenge
Build a navigation heatmap using the Page Visibility API. Identify the three most common navigation paths from your homepage and add prefetch hints for those pages. Measure the reduction in navigation latency.
Real-World Task
Audit your production site for critical above-the-fold resources. Add preload hints for the top two CSS files and the hero image. Measure LCP before and after using Lighthouse.
FAQ
Related Tutorials
- Early Hints — Preload critical assets before the HTML is parsed
- Signed Exchanges — Instant page loads via Google Search prefetch
- Page Rules Intro — URL pattern matching for targeted cache control
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro — security-first tools for the modern web.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro