Course contentsShow
← Web Development
Lesson 1978 of 2,98236. Performance Optimization TechniquesFree lesson

Loading Non-Critical CSS Asynchronously

Implement strategies to defer non-critical CSS using media queries and JavaScript loading techniques.

Loading Non-Critical CSS Asynchronously

What you'll learn: How to defer non-critical CSS so it doesn't block page rendering while still loading all your styles.

The Core Problem

When a browser encounters a <link rel="stylesheet"> tag, it stops rendering the page until that CSS file downloads and parses. This is fine for critical CSS (which you've already inlined), but "non-critical" CSS—styles for below-the-fold content, interactive widgets, or secondary features—shouldn't delay your initial render.

Think of it like building a house: you need walls and a roof immediately (critical CSS), but interior decorating (non-critical CSS) can happen after people move in.

The Media Query Trick

The simplest technique uses the media attribute with a non-matching query, then switches it on load:

<link rel="stylesheet" href="non-critical.css" 
      media="print" 
      onload="this.media='all'">

The browser fetches non-critical.css asynchronously because media="print" doesn't match screen rendering. When loaded, the onload event switches it to media='all', applying the styles without blocking render.

JavaScript-Based Loading

For more control, load CSS via JavaScript:

function loadCSS(href) {
  const link = document.createElement('link');
  link.rel = 'stylesheet';
  link.href = href;
  document.head.appendChild(link);
}

// Load after critical content
loadCSS('secondary-styles.css');

This completely removes render-blocking behavior since the link element is created after initial HTML parsing.

Adding a Fallback

Always include a <noscript> fallback:

<noscript>
  <link rel="stylesheet" href="non-critical.css">
</noscript>

Key Takeaway: Loading non-critical CSS asynchronously using media query tricks or JavaScript insertion prevents unnecessary render blocking, dramatically improving First Contentful Paint and Largest Contentful Paint scores while ensuring all styles eventually load.