Explain Codes LogoExplain Codes Logo

How to Load CSS Asynchronously

web-development
responsive-design
performance
best-practices
Anton ShumikhinbyAnton Shumikhin·Dec 24, 2024
TLDR

To achieve superior web performance, employ asynchronous CSS loading. Start with inlining critical CSS, then use link rel="preload" for the rest. Switch non-blocking styles from media="print" to "all" post-load via onload. Keep accessibility in check with a noscript fallback. Have a look at the condensed solution:

<style>/* Inline critical CSS */</style> <link rel="preload" href="async.css" as="style" onload="this.rel='stylesheet'; this.onload=null;" media="print"> <noscript><link rel="stylesheet" href="async.css"></noscript>

Asynchronous loading using onload and media attributes

By utilizing the onload attribute in the link element, your CSS files load asynchronously without blocking rendering. The media attribute starts as an inactive state like "print", preventing immediate application of styles, and switches to "all" once the CSS is ready to go.

<!-- CSS ninja in action here, silently loading the stylesheet --> <link rel="stylesheet" href="async.css" media="print" onload="this.media='all';this.onload=null;">

This method affirms that while CSS loads in the background, your webpage remains responsive and ready for interaction.

Layering user experience with progressive enhancement

To handsomely enhance web usability, apply the principles of progressive enhancement. First, serve the core content and lazy-load the remaining styles. Leverage JavaScript to append link elements after the window load event. Doing so conceals the flash of unstyled content (FOUC) offering a smooth user experience.

Here's a JavaScript snippet that appends CSS after window loads:

// Can't touch this! Loading styles after window load. window.addEventListener('load', function() { var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = 'async.css'; document.head.appendChild(link); });

Resource management and performance enhancement

A tricky balance between the benefits of enhancing performance and maintaining fast, lightweight assets is required. Merging rel="preload" with the aforementioned async techniques stands beneficial, if used wisely. Preload only highly significant stylesheets that impact the initial page load.

Consider potential roadblocks while preloading. Large CSS files, for instance, can inadvertently delay the loading of other resources. In your optimization strategy, prune and split CSS files, keeping only what's necessary in each bundle.

Accessible and conflict-free asynchronous loading

While implementing async CSS, ensure that your site remains accessible to users. Those who have JavaScript disabled should still be able to observe the styled content. The noscript tag offers an alternate, accessible CSS loading pathway:

<!-- Fallback for our disabled-JS friends --> <noscript><link rel="stylesheet" href="async.css"></noscript>

Keep in mind that asynchronous methods and content security policies (CSP) can sometimes lock horns. Stick to your CSP rules to avoid conflicts.

Asynchronous loading of multiple CSS files

To load multiple CSS files asynchronously, pair a JavaScript loop with the techniques discussed earlier. This combo keeps your CSS files non-blocking while optimizing page performance.

Here's how you can load multiple CSS files asynchronously:

// Juggling CSS files? No problem! var cssFiles = ['async1.css', 'async2.css', 'async3.css']; cssFiles.forEach(function(cssFile) { var link = document.createElement('link'); link.rel = 'stylesheet'; link.href = cssFile; link.media = 'print'; link.onload = function() { this.media='all'; }; document.head.appendChild(link); });

References

  1. rel=preload - HTML: HyperText Markup Language | MDN — understanding how rel=preload boosts your page performance.
  2. Defer non-critical CSS | Articles | web.dev — deep dive into deferring non-critical CSS for leaner page loading times.
  3. GitHub - filamentgroup/loadCSS: Load CSS asynchronously — practical guide for asynchronously loading CSS.
  4. async vs defer attributes - Growing with the Web — an informative guide about async and defer attributes in scripts.
  5. Understanding Critical CSS — Smashing Magazine — insights about the impact of Critical CSS on rendering performance.
  6. Using media queries - CSS: Cascading Style Sheets | MDN — learning about CSS media queries for responsive design and conditional CSS loading.
  7. PageSpeed Insights — using this tool to assess your web page's performance after optimizing.