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
.