0
0
HtmlHow-ToBeginner · 3 min read

How to Preload Resources in HTML for Faster Loading

To preload resources in HTML, use the <link rel="preload" href="resource" as="type"> tag in the <head>. This tells the browser to fetch important files early, improving page speed and smoothness.
📐

Syntax

The <link> tag with rel="preload" is used to preload resources. The href attribute specifies the resource URL, and as defines the type of resource (like script, style, image, or font).

Example parts:

  • rel="preload": tells the browser to preload.
  • href="URL": the resource to load early.
  • as="type": the kind of resource for correct handling.
html
<link rel="preload" href="style.css" as="style">
💻

Example

This example preloads a CSS file and a JavaScript file to make the page load faster and smoother.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Preload Example</title>
  <link rel="preload" href="styles.css" as="style">
  <link rel="preload" href="script.js" as="script">
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <h1>Hello, preload!</h1>
  <script src="script.js"></script>
</body>
</html>
Output
<h1>Hello, preload!</h1>
⚠️

Common Pitfalls

Common mistakes when preloading resources include:

  • Not specifying the correct as attribute, which can cause the browser to ignore the preload.
  • Preloading resources that are not used soon, wasting bandwidth.
  • Forgetting to include the actual resource later (like a stylesheet or script), so preload does nothing.
html
<!-- Wrong: missing 'as' attribute -->
<link rel="preload" href="image.png">

<!-- Right: specify 'as' for correct resource type -->
<link rel="preload" href="image.png" as="image">
📊

Quick Reference

AttributeDescriptionExample Values
relDefines the relationship; use 'preload' to preload resourcespreload
hrefURL of the resource to preloadstyles.css, script.js, image.png
asType of resource for proper handlingscript, style, image, font
crossoriginNeeded for fonts or cross-origin resourcesanonymous

Key Takeaways

Use in the to tell the browser to load important resources early.
Always specify the correct 'as' attribute to ensure the browser handles the resource properly.
Preload only resources needed soon to avoid wasting bandwidth.
Remember to include the actual resource later in your HTML or CSS for preload to be effective.
Use 'crossorigin' attribute when preloading fonts or cross-origin files.