How to load up CSS files using JavaScript?

Spread the love

Sometimes, we want to load up CSS files using JavaScript.

In this article, we’ll look at how to load up CSS files using JavaScript.

How to load up CSS files using JavaScript?

To load up CSS files using JavaScript, we use createElement.

For instance, we write

const cssId = "myCss";
if (!document.getElementById(cssId)) {
  const head = document.head;
  const link = document.createElement("link");
  link.id = cssId;
  link.rel = "stylesheet";
  link.type = "text/css";
  link.href = "http://website.example/css/stylesheet.css";
  link.media = "all";
  head.appendChild(link);
}

to call createElement to create a link element.

Then we set the attributes with the same name as the property names with

link.id = cssId;
link.rel = "stylesheet";
link.type = "text/css";
link.href = "http://website.example/css/stylesheet.css";
link.media = "all";

And then we call head.appendChild to append the link as the last child of the head element.

Conclusion

To load up CSS files using JavaScript, we use createElement.

Leave a Reply

Your email address will not be published.