Categories
JavaScript Answers

How to load up CSS files using JavaScript?

Spread the love

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

For instance, we write

const link = document.createElement("link");
link.href = src;
link.rel = "stylesheet";
document.head.append(link);

to call createElement to create a link element.

And then we set its href and rel attributes by setting the properties with the same name.

Then we call document.head.append to append the link element as the last child of the head element.

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 *