0
0
HtmlHow-ToBeginner · 3 min read

How to Preconnect in HTML for Faster Resource Loading

Use the <link rel="preconnect" href="URL"> tag in the HTML <head> to tell the browser to start connecting early to a resource. This helps speed up loading by reducing wait time for DNS lookup, TCP handshake, and TLS negotiation.
📐

Syntax

The preconnect link tag has a simple syntax:

  • rel="preconnect": Tells the browser to start connecting early.
  • href="URL": The address of the resource to connect to.
  • Optional attributes like crossorigin can be added if the resource requires CORS.
html
<link rel="preconnect" href="https://example.com" crossorigin>
💻

Example

This example shows how to preconnect to Google Fonts to speed up font loading:

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Preconnect Example</title>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
  <style>
    body {
      font-family: 'Roboto', sans-serif;
      font-size: 1.5rem;
      padding: 1rem;
    }
  </style>
</head>
<body>
  <p>This page preconnects to Google Fonts domains to load the Roboto font faster.</p>
</body>
</html>
Output
A webpage with the text "This page preconnects to Google Fonts domains to load the Roboto font faster." displayed in the Roboto font.
⚠️

Common Pitfalls

  • Not using crossorigin when preconnecting to a resource that requires CORS can cause the preconnect to fail.
  • Preconnecting to too many domains can waste browser resources and slow down the page.
  • Using preconnect for resources that are not used soon after page load offers no benefit.
html
<!-- Wrong: Missing crossorigin for fonts.gstatic.com -->
<link rel="preconnect" href="https://fonts.gstatic.com">

<!-- Right: Add crossorigin attribute -->
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
📊

Quick Reference

AttributeDescriptionExample
relRelationship type, must be 'preconnect'rel="preconnect"
hrefURL of the resource to connect earlyhref="https://example.com"
crossoriginOptional, needed for CORS-enabled resourcescrossorigin

Key Takeaways

Use in the to start early connections to important resources.
Add the crossorigin attribute when preconnecting to resources that require CORS.
Avoid preconnecting to too many or unused domains to prevent wasting browser resources.
Preconnect helps reduce delays caused by DNS, TCP, and TLS handshakes.
Place preconnect tags before resource requests for best performance.