3

I want to load an external javascript file into the page and make sure its not cached. I do not have access to php so I cant generate a random string after the filename.

In PHP the script would look like this:

<script src="http://site.com/cool.js?<?php echo $randomnumber; ?>"></script>

Is there a way to do something like that using only javascript?

6
  • 3
    You can configure your server to set appropriate headers. It's not possible to do it from the browser side. Commented Feb 15, 2013 at 15:25
  • Does the script tag already exist? or are you adding a new script tag with javascript. Commented Feb 15, 2013 at 15:25
  • 2
    Use jQuery's $.getScript and append a random string to the end of the filename - api.jquery.com/jQuery.getScript Commented Feb 15, 2013 at 15:28
  • @JayBlanchard ah - I interpreted "I do not have access to php" to mean "I do not have access to the source"; if the page code can be changed then yes that will work fine. Commented Feb 15, 2013 at 15:31
  • 3
    @JayBlanchard getScript already does that. From the docs: Be default, $.getScript() sets the cache setting to false. This appends a timestamped query parameter to the request URL to ensure that the browser downloads the script each time it is requested Commented Feb 15, 2013 at 15:33

4 Answers 4

20

Use jQuery's getScript instead of a script tag.

$.getScript("http://example.com/cool.js");

or pure JavaScript

var scr = document.createElement("script");
scr.src = "http://example.com/cool.js" + "?ts=" + new Date().getTime();
document.getElementsByTagName("head")[0].appendChild(scr);
Sign up to request clarification or add additional context in comments.

3 Comments

Awesome!!! I was beating my head against the wall trying to figure out how to get Edge to stop caching. None of the anti-caching HTTP headers were working. "?ts=" is brilliant!! Thank you so much.
Cool solution but: "Uncaught ReferenceError: ANYVAR is not defined". Seems the JS file is loaded after other <scripts> although JQuery.Ready :/
@Extrangeplanet of course it will be loaded AFTER ready
5

Just append a random string to the src of the script like you do with PHP. For this you need to inject the <script> tag with JS.

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'path/to/file?' + new Date().getMilliseconds();

document.getElementsByTagName('head')[0].appendChild(s);

5 Comments

FYI: getMilliseconds() can repeat if you are really lucky.
Valid point to some extent, but chances are really low since you don't repeat this operation many many times within the same context (browser, time, etc.).
The birthday paradox says that with as few as 32 requests, there is a 50% chance that a value repeats. The fact that the request isn't issued very often just means that if a repeated value does match a cached version, it is more likely to be an old version of the script rather than a recent version. Better to use a longer string, like getTime() that could only repeat over a very short time frame. getMilliseconds() is effectively just a very low-entropy random number when used this way.
You are absolutely right in that this exact way of doing this does not guarantee a good level of uniqueness. (So you might end up receiving a cached copy of the script if the appended random happens to be the same as a previous value.) My goal here was not to provide sufficient uniqueness. But anyway, here is a better random to add to the request URL: parseInt(Math.random().toString().substr(-5))
@marekful Why wouldn't I repeat this operation 1000 times in the same browser session? If my server is providing periodic real-time updates, then it would take only a few minutes to reach 1000.
1

Sure, just insert a script tag into the DOM, with JS generating the value, e.g.

var d = new Date.getTime();
$('head').append('<scri' + 'pt src="http://....?cachebuster=' + d + '"></scr' + 'ipt>');

Comments

1

You can try <meta http-equiv="Cache-Control" content="no-store" />. There is another ticket talking about this: stackoverflow

1 Comment

I think this is for the whole page. Not for a single JavaScript resource.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.