Avatar of WestCoast_BC
WestCoast_BC
Flag for Canada asked on

What is the best way to force a reload of a style sheet

If I change my style sheet (.css file) I want to force a reload of the file. What is the best way to do this? Is it by adding a query string? Ie:
<link href="style.css?ver=2" rel="stylesheet">

and then changing ver= each time my style sheet changes?

Should I do the same thing for js files?
CSSHTMLJavaScript

Avatar of undefined
Last Comment
Julian Hansen

8/22/2022 - Mon
WestCoast_BC

ASKER
Does it matter what the string is that I pass? Is it more efficient to pass a number or could I pass a string like a guid?
Julian Hansen

The style sheet change should happen automatically.

Consider this example
Head
<link id="target" href="css/custom.css" rel="stylesheet" />

Open in new window

HTML
<button id="switch" class="btn btn-primary">Switch Stylesheet</button>

Open in new window

JavaScript
<script>
var target = document.getElementById('target');
var href1 = target.href;
var href2 = target.href.replace('custom.css','custom-dark.css');

document.getElementById('switch').addEventListener('click', function() {
	target.href = target.href == href1 ? href2 : href1;
});
</script>

Open in new window


Working sample here
WestCoast_BC

ASKER
My issue is caching. I am finding that if I change the css file unless I change the query string passed I am finding that the new style sheet is not being loaded automatically. I think the above comment is for changing which style sheet is loaded, which is not my problem.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER CERTIFIED SOLUTION
Julian Hansen

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Julian Hansen

Re js files - yes same procedure.

Take a look at Wordpress - this is exactly what they do to version the scripts and css files in a WordPress site.