Michiel Cornille
Michiel Cornille

Reputation: 2097

JS file in chrome is never cached

I dynamically create javascript files on the server that contain translated strings. When I look at chrome inspector this file never gets cached, (other actual JS files that are in the Scripts folder do get cached) *Why isn't it?*

<script src="somepath/Scripts/translate-nl-BE.js"></script>
or
<script src="somepath/Scripts/translate-en-GB.js"></script>

this is mapped to the following MVC action:

[HttpGet]        
public ActionResult TranslateJS(string culturecode) {
     ViewBag.JSCulture = culturecode;
     Response.ContentType = "text/javascript";
     return PartialView("TranslateJS");
}

here's the view:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<dynamic>" %>
<%
    string culturecode = ViewBag.JSCulture;
%>
var translations = <%=new System.Web.Script.Serialization.JavaScriptSerializer().Serialize((ViewBag.Translate as List<ERPManager.TranslationService.FlatTranslation>).Where(x=>x.CultureCode==culturecode).ToDictionary(t=>t.Key,f=>f.Value)) %>;

this basically just serializes a json array (I know this looks dirtyer than just returning a jsonresult but i can't ajax call this file, it need sto be linked into a script tag

This is the response I get from the server:

Cache-Control:private
Content-Length:10987
Content-Type:text/javascript; charset=utf-8
Date:Thu, 04 Apr 2013 10:15:11 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
X-Powered-By:ASP.NET

here's a preview of the file that get's returned: it's basically just a key value dictionary of translations.

var translations = {"vertaald":"Vertaald","gerelateerd":"Gerelateerd","details":"Details"};

Upvotes: 2

Views: 614

Answers (1)

Liam
Liam

Reputation: 29750

It sounds like what you want is an expires HTTP header

You can set this in your MVC code:

[HttpGet]        
public ActionResult TranslateJS(string culturecode) {
   ViewBag.JSCulture = culturecode;
   Response.ContentType = "text/javascript";
   Response.Expires = (60*24);//24 hours
   return PartialView("TranslateJS");
}

Bear in mind if you set an expires header the browser will not request the file again until after the cached content has "expired". Use with caution!

Upvotes: 2

Related Questions