I want to reload all CSS stylesheets in a html page via javascript, without reloading the page.
I need this only while developing to reflect css changes without refreshing the page all time.
A possible solution is to add a ?id=randomnumber
suffix to the css hrefs with javascript, but I don't want to do that.
I want to reload the stylesheet some way, without changing it's url, and the browser will decide if it needs to load a new version of that css or not (if server responds with a 304 - Not modified
).
How to accomplish this?
Anytime you make changes to CSS, JavaScript and are viewing the page you've updated - you will see this concern. You can force a refresh by pressing CTRL+F5 on the browser and that will get the latest version.
In Chrome, you can do a hard reload by opening the console (F12 key) and then right-clicking on the reload button to get a menu with additional reload options.
But, if you're not using it, and you just need to reload that one CSS or JS file occasionally in your own browser... just open it in its own tab and hit SHIFT-reload (or CTRL-F5)!
Information: JavaScriptJavaScript can interact with stylesheets, allowing you to write programs that change a document's style dynamically. There are three ways to do this: By working with the document's list of stylesheets—for example: adding, removing or modifying a stylesheet.
In plain Javascript:
var links = document.getElementsByTagName("link");
for (var x in links) {
var link = links[x];
if (link.getAttribute("type").indexOf("css") > -1) {
link.href = link.href + "?id=" + new Date().getMilliseconds();
}
}
In jQuery:
$("link").each(function() {
if $(this).attr("type").indexOf("css") > -1) {
$(this).attr("href", $(this).attr("href") + "?id=" + new Date().getMilliseconds());
}
});
Make sure you load this function after the DOM tree is loaded.
First, add an id (if not present) to your stylesheet link tags like so:
<link id="mainStyle" rel="stylesheet" href="style.css" />
Next, in Javascript (also utilizing jQuery) add the following function:
function freshStyle(stylesheet){
$('#mainStyle').attr('href',stylesheet);
}
Lastly, trigger the function on your desired event:
$('#logo').click(function(event){
event.preventDefault();
var restyled = 'style.css';
freshStyle(restyled);
});
By updating the value of the linked stylesheet, even if it's the same value, you force the client to look again; when it does, it'll see and (re)load the latest file.
If you're running into issues with cache, then try appending a random (psuedo) version number to your filename like this:
var restyled = 'style.css?v='+Math.random(0,10000);
Hope this helps. Dillen's examples above also work, but you can use this if you want to just target one or a set of stylesheets with minor adjustments.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With