I am dynamically creating a javascript file on my web server whose contents are different with each request. I need a way to force a browser to download the javascript file each time (ie. set the cache or whatever in the past).
Setting the name to a random name is not really an option because there will be some users who would constantly access this file and I don't want to clog up their cache with a thousand random js files!
Thanks
How to set a javascript file to expire in the past?
Moderator: General Moderators
- Kieran Huggins
- DevNet Master
- Posts: 3635
- Joined: Wed Dec 06, 2006 4:14 pm
- Location: Toronto, Canada
- Contact:
Re: How to set a javascript file to expire in the past?
append a "?" to the src attribute - this fools the browser into thinking it's being freshly generated (because you're passing it arguments like a script, even though there aren't any) and therefore won't use a cached copy:
Note: The actual file name wouldn't have a "?" on the end, obviously.
Code: Select all
<script src="/js/somescript.js?"></script>Re: How to set a javascript file to expire in the past?
I normally do something similar as Kieran has said, I usually give it some type of number or date of the file.
Code: Select all
<script src="/js/somescript.js?v=<?php echo $JsVersion; ?>"></script>Re: How to set a javascript file to expire in the past?
Thanks for that - I ended up finding a solution late last night and did exactly that (although hadn't yet tested it properly).
Pity it took me so many hours to find such a simple solution!!
For the record, I ended up appending a PHP timestamp after the '?' to make it unique, but if the '?' on it's own does the trick then I'll go with that - saves a tiny bit of extra processing.
Pity it took me so many hours to find such a simple solution!!
For the record, I ended up appending a PHP timestamp after the '?' to make it unique, but if the '?' on it's own does the trick then I'll go with that - saves a tiny bit of extra processing.