Link to home
Start Free TrialLog in
Avatar of WestCoast_BC
WestCoast_BCFlag 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?
Avatar of WestCoast_BC
Flag of Canada image


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?
Avatar of Julian Hansen
The style sheet change should happen automatically.

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

Open in new window

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

Open in new window

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;

Open in new window

Working sample here
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.
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.