1

Background

An MVC 4 application needs to include JavaScript that is generated from the database. The generated file is relatively large, and changes only occasionally (changes every 2-10 days).

The accepted answer of

Generate javascript file on the fly in asp.net mvc

provides a good framework for generating the JavaScript. However, the URL of the JavaScript resource is static. As I understand it, the browser will cache that resource. That caching can be controlled by the OutputCacheAttribute.

Question

How can I cause the browser cache to expire whenever the generated JavaScript changes, similar to the way that bundles work? A SqlDependency for the OutputCacheAttribute is not an option.

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • Version query string in the script URL? E.g. `foo.js?v=1234567`. (When your JS file changes, append a different query string. This forces the browsers to request it.) – Šime Vidas Feb 20 '13 at 20:19
  • Alternatively, name the javascript file something to do with the date it was generated. – Colin DeClue Feb 20 '13 at 20:22
  • @ColinDeClue: The name of the JavaScript resource is the URL of the controller, is it not? Not sure how to give the JavaScript resource a different name. – Eric J. Feb 20 '13 at 20:23
  • @ŠimeVidas: The file doesn't have well-defined "versions". The database is queried when the JavaScript must be constructed. – Eric J. Feb 20 '13 at 20:24
  • @EricJ. Hm, the timestamp when the DB was last queried could serve as the version identifier... – Šime Vidas Feb 20 '13 at 20:26
  • A mere guess but I'd give a go to the common _random query string_ method as in @Šime Vidas's comment. Just to see what happens if you append `?something` to that resource name. – marekful Feb 20 '13 at 20:38

1 Answers1

1

I have a similar situation, and what I do is append a random Guid to the end of the query string in the script tag every time I regenerate the JavaScript file.

For Example:

<script type="text/javascript" src="/scripts/generated.js?id=7c97aa32-29d9-dd11-a926-001d096d84f2"></script>

You could use a random string or even a time-stamp, as long as the query parameter is changed,the new script file will be downloaded.

Jack
  • 1,319
  • 8
  • 16
  • I don't really want to generate a static file, but rather have a controller action return the JavaScript (which would be cached). I guess I could apply the same principal using a hash of the generated script or the generation timestamp. – Eric J. Feb 20 '13 at 23:27
  • You're right, the same principal will work for a non-static file. As long as there's a change in the query string appended to the static url of the JavaScript resource the browser will download the updated file. A time-stamp or hash should both do the trick. – Jack Feb 20 '13 at 23:41