How to Preload Fonts in HTML for Faster Loading
To preload fonts in HTML, use the
<link rel="preload" as="font" href="font-file.woff2" type="font/woff2" crossorigin> tag inside the <head>. This tells the browser to load the font early, improving page speed and avoiding flash of unstyled text.Syntax
The preload syntax uses a <link> tag with specific attributes:
rel="preload": Tells the browser to load the resource early.as="font": Specifies the resource type is a font.href="font-file.woff2": URL to the font file.type="font/woff2": MIME type of the font file.crossorigin: Needed if the font is loaded from a different origin to allow proper fetching.
html
<link rel="preload" href="/fonts/myfont.woff2" as="font" type="font/woff2" crossorigin>
Example
This example shows how to preload a font and then use it in CSS. The font file is loaded early to avoid delays when rendering text.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Preload Font Example</title> <link rel="preload" href="/fonts/OpenSans-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous"> <style> @font-face { font-family: 'Open Sans'; src: url('/fonts/OpenSans-Regular.woff2') format('woff2'); font-weight: normal; font-style: normal; font-display: swap; } body { font-family: 'Open Sans', sans-serif; font-size: 1.25rem; padding: 2rem; } </style> </head> <body> <p>This text uses the preloaded Open Sans font.</p> </body> </html>
Output
A webpage with a paragraph displayed in the Open Sans font, loaded quickly without delay.
Common Pitfalls
Common mistakes when preloading fonts include:
- Not using
crossoriginwhen loading fonts from another domain, causing the font to fail loading. - Forgetting to match the
typeattribute with the font file format. - Not including the
as="font"attribute, which can prevent proper prioritization. - Preloading fonts that are not actually used on the page, wasting bandwidth.
html
<!-- Wrong: Missing crossorigin --> <link rel="preload" href="https://example.com/fonts/font.woff2" as="font" type="font/woff2"> <!-- Right: Include crossorigin --> <link rel="preload" href="https://example.com/fonts/font.woff2" as="font" type="font/woff2" crossorigin="anonymous">
Quick Reference
Remember these tips when preloading fonts:
- Always use
rel="preload"withas="font". - Include
typematching your font format (e.g.,font/woff2). - Add
crossoriginif fonts come from a different origin. - Use
@font-facein CSS to apply the font. - Preload only fonts actually used on the page.
Key Takeaways
Use in the to load fonts early.
Always include the correct
type and crossorigin attributes.Preloading improves page speed and avoids flash of unstyled text.
Match preloaded fonts with CSS @font-face declarations.
Only preload fonts that are actually used on the page.