Sometimes, we want to reload CSS without reloading the page with JavaScript.
In this article, we’ll look at how to reload CSS without reloading the page with JavaScript.
How to reload CSS without reloading the page with JavaScript?
To reload CSS without reloading the page with JavaScript, we can loop through the link
elements and update their href
attribute values.
For instance, we write
const reloadCss = () => {
const links = document.getElementsByTagName("link");
for (const link of links) {
if (link.rel === "stylesheet") {
link.href += "";
}
}
};
to define the reloadCss
function.
In it, we get all the link
elements with getElementsByTagName
.
Then we loop through the links
with a for-of loop.
In it, we check if the rel
attribute of each link
is 'stylesheet'
with
link.rel === "stylesheet"
If it is, then we update the href
attribute with
link.href += ""
to reload the CSS referenced by the link
element.
Conclusion
To reload CSS without reloading the page with JavaScript, we can loop through the link
elements and update their href
attribute values.