We help IT Professionals succeed at work.

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

WestCoast_BC
WestCoast_BC asked
on
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?
Comment
Watch Question

Author

Commented:
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?
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
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

Author

Commented:
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.
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
just add a url variable to the end

<link rel="stylesheet" href="http://yourdomain.com/css/stylesheet.css?v=1.01">

Open in new window

Just change the number on the end whenever your stylesheet changes.

Changing v=1.01 => v=1.02 is a completely different URL as far as the Browser is concerned but will still return the same Stylesheet.
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
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.