How to load CSS files using JavaScript?

Loading CSS files dynamically using JavaScript allows you to change page themes, implement dark/light mode toggles, or conditionally load styles based on user preferences. This technique is useful when you need to switch between different stylesheets without page refresh.

Syntax

/* Create link element */
const link = document.createElement("link");
link.href = "path/to/stylesheet.css";
link.rel = "stylesheet";
link.type = "text/css";

/* Append to head */
document.head.appendChild(link);

Example 1: Loading CSS on Window Load

This example demonstrates loading a CSS file automatically when the page finishes loading

<!DOCTYPE html>
<html>
<head>
    <script>
        window.onload = () => {
            const headTag = document.getElementsByTagName('head')[0];
            const linkForCSSFile = document.createElement("link");
            linkForCSSFile.href = '/cssfilenew.css';
            linkForCSSFile.type = 'text/css';
            linkForCSSFile.rel = 'stylesheet';
            headTag.appendChild(linkForCSSFile);
        };
    </script>
</head>
<body>
    <h1>Dynamic CSS Loading</h1>
    <p>This page loads CSS dynamically on window load</p>
</body>
</html>

The CSS file (cssfilenew.css) contains

body {
    background-color: rgb(110, 187, 197);
    font-family: Arial, sans-serif;
}

h1 {
    color: rgb(15, 15, 87);
    text-align: center;
}

p {
    color: rgb(197, 31, 31);
    font-size: 18px;
}
The page loads with a light blue background, dark blue centered heading, and red paragraph text applied from the dynamically loaded CSS file.

Example 2: Loading Different CSS Files with Buttons

This example shows how to switch between different themes using button clicks

<!DOCTYPE html>
<html>
<head>
    <script>
        function loadTheme1() {
            removeExistingCSS();
            const headTag = document.getElementsByTagName('head')[0];
            const linkForCSSFile = document.createElement("link");
            linkForCSSFile.href = '/theme1.css';
            linkForCSSFile.type = 'text/css';
            linkForCSSFile.rel = 'stylesheet';
            linkForCSSFile.id = 'dynamic-css';
            headTag.appendChild(linkForCSSFile);
        }

        function loadTheme2() {
            removeExistingCSS();
            const headTag = document.getElementsByTagName('head')[0];
            const linkForCSSFile = document.createElement("link");
            linkForCSSFile.href = '/theme2.css';
            linkForCSSFile.type = 'text/css';
            linkForCSSFile.rel = 'stylesheet';
            linkForCSSFile.id = 'dynamic-css';
            headTag.appendChild(linkForCSSFile);
        }

        function removeExistingCSS() {
            const existingLink = document.getElementById('dynamic-css');
            if (existingLink) {
                existingLink.remove();
            }
        }
    </script>
</head>
<body>
    <h1>Theme Switcher Demo</h1>
    <p>Click buttons to load different CSS themes</p>
    <button onclick="loadTheme1()">Load Green Theme</button>
    <button onclick="loadTheme2()">Load Blue Theme</button>
</body>
</html>

Theme 1 CSS (theme1.css)

body {
    background-color: rgb(167, 197, 110);
    padding: 20px;
}

h1 {
    color: rgb(87, 15, 55);
}

p {
    color: rgb(4, 59, 20);
}

button {
    background-color: #4CAF50;
    color: white;
    padding: 10px 15px;
    margin: 5px;
    border: none;
    border-radius: 5px;
}

Theme 2 CSS (theme2.css)

body {
    background-color: rgb(110, 187, 197);
    padding: 20px;
}

h1 {
    color: rgb(15, 15, 87);
}

p {
    color: rgb(197, 31, 31);
}

button {
    background-color: #2196F3;
    color: white;
    padding: 10px 15px;
    margin: 5px;
    border: none;
    border-radius: 5px;
}
Initially, the page has no custom styling. Clicking "Load Green Theme" applies green background with styled buttons. Clicking "Load Blue Theme" switches to blue background with different button colors.

Best Practices

  • Always remove existing dynamic CSS before adding new ones to prevent conflicts
  • Use unique IDs for dynamically created link elements
  • Handle loading errors with event listeners
  • Consider using CSS custom properties for simpler theme switching

Conclusion

Dynamic CSS loading with JavaScript enables flexible theme switching and conditional styling. Use document.createElement("link") to create stylesheet links and append them to the document head for immediate effect.

Updated on: 2026-03-15T16:47:18+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements