Reputation: 113
using HTML5+CSS3+jQuery.
Since I am changing my CSS file frequently, I would like to force users' browsers always to fetch the CSS file and never use the cached version.
I found that I should write something like this:
<link rel="stylesheet" type="text/css" href="index.css?t=[...some unique id...]"/>
How can I automatically generate such unique Id? ( maybe current time?)
Thanks
Upvotes: 0
Views: 67
Reputation: 766
For your particular issue, you could inject the link via javascript using ticks. In this example the code would insert the css as the last styleset processed. I would recommend doing this on the back-end though.
<html>
<head>
<title>Test</title>
<script type="text/javascript">
var sourceName = 'test.css?v=' + ((new Date().getTime() * 10000) + 621355968000000000); // using ticks
var linkElement = document.createElement('link');
linkElement.setAttribute('type', 'text/css');
linkElement.setAttribute('rel', 'stylesheet');
linkElement.setAttribute('href', sourceName);
document.getElementsByTagName('head')[0].appendChild(linkElement);
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
I tested it before publishing it and went through various methods. Many did not execute the href change. It only seemed to execute if it was injected into the DOM.
Upvotes: 0
Reputation: 9907
If your CSS is small and dynamic, your best solution would be to inject it inline in the <head>
using <style>
tags: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/style
This way your styles will be updated on every page refresh and you will not need to wait for an additional http request.
For example, if your stylesheet looks like this:
/* This stuff hardly ever changes */
html {
background-color: white;
font-size: 16px;
}
/* This stuff changes all the time */
body {
background-image: url('todays-image.png');
}
And your html looks something like this:
<html>
<head>
<title>My Page</title>
<link rel="stylesheet" type="text/css" href="index.css" />
</head>
<body>
<h1>My Page</h1>
</body>
</html>
Change the css to look like this:
/* This stuff hardly ever changes */
html {
background-color: white;
font-size: 16px;
}
And the html to look like this:
<html>
<head>
<title>My Page</title>
<link rel="stylesheet" type="text/css" href="index.css" />
<style>
/* This stuff changes all the time */
body {
background-image: url('todays-image.png');
}
</style>
</head>
<body>
<h1>My Page</h1>
</body>
</html>
If all of the contents of index.css
change frequently, you can remove the file entirely and remove the link
tag.
Upvotes: 1
Reputation: 425
You can use a server timestamp
<link rel="stylesheet" type="text/css" href="style.css?<?php echo date('l jS \of F Y h:i:s A'); ?>" />
A better Idea is to use a version of your css:
<link rel="stylesheet" type="text/css" href="style.css?version=<?php echo $CSS_VERSION; ?>" />
Upvotes: 1