Categories
JavaScript Answers

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 create a link element with createElement.

For instance, we write

const element = document.createElement("link");
element.setAttribute("rel", "stylesheet");
element.setAttribute("type", "text/css");
element.setAttribute("href", "external.css");
document.head.appendChild(element);

to create a link element with createElement.

Then we call setAttribute to set the rel, type, and href attribute values.

Finally, we call document.head.appendChild to append the link element as the last child element of the head element.

Conclusion

To load up CSS files using JavaScript, we create a link element with createElement.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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