4 Ways To Dynamically Load & Replace CSS (Simple Examples)

Welcome to a quick tutorial on how to dynamically load CSS files. So you have a project that requires some sorcery to load or change the CSS after the page is loaded? Or maybe you want to lazy load some CSS files? We actually don’t need a third-party library, nor do confusing imports.

To load CSS files dynamically, we can manually insert a <link> tag:

  • var ss = document.createElement("link");
  • ss.rel = "stylesheet";
  • ss.type = "text/css";
  • ss.href = "STYLES.CSS";
  • document.head.appendChild(ss);

That covers the quick basics, but let us walk through a few more examples in this guide – Read on!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

TLDR – QUICK SLIDES

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

EXAMPLE CODE DOWNLOAD

Click here to download the example code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

 

DYNAMICALLY LOAD CSS

All right, let us now get into the various examples of dynamically loading CSS with Javascript.

 

1) INSERT LINK TAG

1a-load-css.html
<!-- (A) TEST TEXT BLOCK -->
<p id="demo">FOO BAR!</p>
<input type="button" onclick="loadcss()" value="Load CSS">
 
<!-- (B) DYNAMICALLY LOAD CSS -->
<script>
function loadcss () {
  // (B1) CREATE NEW <LINK> TAG
  var stylesheet = document.createElement("link");
  stylesheet.rel = "stylesheet";
  stylesheet.type = "text/css";
  stylesheet.href = "1b-demo.css";
 
  // (B2) OPTIONAL - ON SUCCESSFUL LOAD & ERROR
  stylesheet.onload = () => alert("CSS loaded");
  stylesheet.onerror = e => alert("Error loading CSS");
 
  // (B3) APPEND <LINK> TAG TO <HEAD>
  document.head.appendChild(stylesheet);
}
</script>
1b-demo.css
#demo {
  font-weight: bold;
  font-size: 2em;
  color: red;
}

As in the introduction above, this is one of the most common ways to load a CSS file in Javascript – We manually create a <link> tag and insert it into the <head> section.

 

 

2) CREATE CSS STYLE SHEET

2-create-css.html
<!-- (A) TEST TEXT BLOCK -->
<p id="demo">FOO BAR!</p>
<input type="button" onclick="insertcss()" value="Insert CSS">
 
<!-- (B) DYNAMICALLY CREATE CSS -->
<script>
function insertcss () {
  let stylesheet = new CSSStyleSheet();
  stylesheet.insertRule("#demo { color: red; font-weight: 700; }");
  document.adoptedStyleSheets = [stylesheet];
}
</script>

Alternatively, this is the “Object-Oriented” way to create a new stylesheet and insert it into the page.

 

 

3) REPLACING CSS STYLES

3-replace-css.html
<!-- (A) CSS STYLE -->
<style>
#demo { color: blue; }
</style>

<!-- (B) TEST TEXT BLOCK -->
<p id="demo">FOO BAR!</p>
<input type="button" onclick="replacecss()" value="Replace CSS">
 
<!-- (C) DYNAMICALLY REPLACE CSS -->
<script>
function replacecss () {
  let stylesheet = document.styleSheets[0];
  stylesheet.deleteRule(0);
  stylesheet.insertRule("#demo { color: red; font-weight: 700; }");
}
</script>

If you want to replace an existing style, this is one of the possibilities… Although I will say that this is not the best idea – If you are creating a switchable theme of sorts, use CSS variables instead.

P.S. There is a stylesheet.replace() and stylesheet.replaceSync() function to replace an existing CSS rule. But it will only work on a new CSSStyleSheet() object.

 

 

4) CSS VARIABLES

4-css-var.html
<!-- (A) CSS STYLES -->
<style>
/* (A1) CSS VARIABLES */
:root {
  --demo-color: black;
  --demo-weight: 500;
}
 
/* (A2) USE CSS VARIABLES */
#demo {
  color: var(--demo-color);
  font-weight: var(--demo-weight);
}
</style>
 
<!-- (B) TEST TEXT BLOCK -->
<p id="demo">FOO BAR!</p>
<input type="button" onclick="cssvar()" value="Replace CSS Var">
 
<!-- (C) DYNAMICALLY CHANGE CSS VAR -->
<script>
function cssvar () {
  document.documentElement.style.setProperty("--demo-color", "red");
  document.documentElement.style.setProperty("--demo-weight", "700");
}
</script>

Lastly, this is the recommended way if you are working with switchable themes. Use CSS variables, it’s just a lot more cleaner than replacing and loading more CSS files.

 

EXTRA BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

UNLOAD CSS?

Yes, we can dynamically load more CSS files, and insert more CSS rules. But as at the time of writing, there doesn’t seem to have smart ways to unload the unused rules. So be clever with the way you work with CSS. Loading more and more CSS files is not the answer to managing dynamic pages – Having a standard template and using CSS variables is the smarter way.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Dynamically Load CSS with Javascript

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *