Load CSS Dynamically

EasyApple

Prompt

Could you explain how to load CSS dynamically in JavaScript?

Understanding Dynamic CSS Loading

Loading CSS dynamically means adding stylesheets to your webpage after it has initially loaded, without requiring a page refresh. This is useful for:

  • Loading CSS based on user actions or device characteristics
  • Improving page load performance by deferring non-critical CSS
  • Implementing theme switching functionality

Common Approaches

1. Creating a Link Element

The most common approach is to create a <link> element and append it to the document's head:

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

// Usage
loadCSS('https://example.com/styles.css');

2. Creating a Style Element

For inline styles, you can create a <style> element:

function addStyles(cssText) {
const style = document.createElement('style');
style.textContent = cssText;
document.head.appendChild(style);
}

// Usage
addStyles('.my-class { color: blue; font-size: 16px; }');

Best Practices

  • Loading Events: Use link.onload and link.onerror to handle successful loading or failures
  • Performance: Load non-critical CSS asynchronously to improve page load times

Sample Interview Answer

Dynamic CSS loading is the process of adding stylesheets to a webpage after the initial page load using JavaScript. This is commonly used for performance optimization and implementing features like theme switching.

The simplest approach is to create a link element and add it to the document head:

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

You can also handle loading events to execute code after the CSS is applied:

link.onload = () => console.log('Styles loaded');

For inline styles, you can create a style element:

const style = document.createElement('style');
style.textContent = '.my-class { color: red; }';
document.head.appendChild(style);

This approach works across all modern browsers and is suitable for most common use cases.

00:00