How to set a javascript file to expire in the past?

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
mcccy005
Forum Contributor
Posts: 123
Joined: Sun May 28, 2006 7:08 pm

How to set a javascript file to expire in the past?

Post by mcccy005 »

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
User avatar
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?

Post by Kieran Huggins »

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:

Code: Select all

<script src="/js/somescript.js?"></script>
Note: The actual file name wouldn't have a "?" on the end, obviously.
User avatar
Zoxive
Forum Regular
Posts: 974
Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan

Re: How to set a javascript file to expire in the past?

Post by Zoxive »

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>
mcccy005
Forum Contributor
Posts: 123
Joined: Sun May 28, 2006 7:08 pm

Re: How to set a javascript file to expire in the past?

Post by mcccy005 »

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.
Post Reply