How to defer CSS loading with JavaScript?

Sometimes, we want to defer CSS loading with JavaScript.

In this article, we’ll look at how to defer CSS loading with JavaScript.

How to defer CSS loading with JavaScript?

To defer CSS loading with JavaScript, we can create a link element with JavaScript.

For instance, we write

const stylesheet = document.createElement("link");
stylesheet.href = "style.css";
stylesheet.rel = "stylesheet";
stylesheet.type = "text/css";
document.head.appendChild(stylesheet);

to create a link element with createElement.

Then we set the href, rel and type properties to set the attributes with the same name.

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

Conclusion

To defer CSS loading with JavaScript, we can create a link element with JavaScript.