Optimizing Resource Loading with DNS Prefetch, Preload, Prefetch, Defer, and Async
DNS Prefetch
DNS prefetching instructs the browser to perform DNS resolution for a specified domain ahead of time. This reduces latency when resources from that domain are later requested. It is particularly effective for CDN domains.
<link rel="dns-prefetch" href="//cdn.example.com">
Preload
The preload directive tells the browser to fetch a critical resource as early as possible, without blocking document parsing. The resource is stored in memory and executed only when a matching <script> or <link> tag is encountered.
<link rel="preload" href="critical.js" as="script">
Prefetch
Prefetching is a low-priority hint for the browser to fetch resources likely to be needed for future navigations. Downloads occur during browser idle time, and resources are cached to disk. Avoid using prefetch for resources required by the current page.
<link rel="prefetch" href="next-page.js">
Script Loading Attributes: Defer and Async
The defer and async attributes modify how external scripts are fetched and executed relative to HTML parsing.
The defer Attribute
Scripts with defer are fetched asynchronously but executed only after the HTML document is fully parsed, just before the DOMContentLoaded event. Execution order among multiple deferred scripts is preserved.
<script src="utility.js" defer></script>
The async Attribute
Scripts with async are fetched asynchronously and executed immediately after download completes, potentially out of order. Use async for independent scripts, such as analytics, where execution order is not critical.
<script src="analytics.js" async></script>
Practical Implementation Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Optimized Page Load</title>
<!-- DNS Prefetch for CDN -->
<link rel="dns-prefetch" href="//assets.cdn.net">
<!-- Preload critical resources -->
<link rel="preload" href="//assets.cdn.net/font.woff2" as="font">
<link rel="preload" href="//assets.cdn.net/app-core.js" as="script">
<!-- Prefetch resources for likely next page -->
<link rel="prefetch" href="//assets.cdn.net/page-two.js">
<style>
/* Inline critical CSS */
</style>
</head>
<body>
<!-- Deferred scripts for non-blocking execution -->
<script src="//assets.cdn.net/app-core.js" defer></script>
<script src="//assets.cdn.net/app-ui.js" defer></script>
</body>
</html>