2012-07-28 71 views
3

朋友,如何避免网站使用本地缓存的JavaScript文件?

最近,我在客户的地方托管了一个网站(使用ASP.Net开发),其中包含许多用于Rich UI交互的JavaScript内容。一切工作正常。但主要的问题是 -

当我在JavaScript文件中做了一些更改并上传它,它不会在客户端的地方生效,因为有网站需要本地缓存的JavaScript文件。

那么,我该如何避免这种情况?

有没有什么技术可以解决我的问题?

回答

-1

有一些技术可以避免浏览器使用缓存过期来缓存资源。

protected void Application_BeginRequest() 
{ 
    //NOTE: Stopping IE from being a caching whore 
    HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false); 
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
    HttpContext.Current.Response.Cache.SetNoStore(); 
    Response.Cache.SetExpires(DateTime.Now); 
    Response.Cache.SetValidUntilExpires(true); 
} 

但对于你的情况,这是不可取的,我认为你的项目仍处于开发阶段,只是避免cntrl + F5通过资源的重新加载和缓存资源被删除并重新加载再次,你不应该执行这一补救措施因为这会降低你的网站性能。

更简单和更合理的解决方案是告诉您的客户合作,并在需要查看最近网站变化时按cntrl + F5,此后当网站完成时,不需要再做任何操作,或者您可以在开发阶段仅实现以上给定的代码,并在使您的网站生效之前将其删除。

+0

CTRL + F5是不能接受的,先生。 – Julian 2012-07-28 05:44:31

+0

这只是一个建议,上面给出的代码可以替代地使用。 – yogi 2012-07-28 05:46:59

2

了一些研究之后,我们来到了头的下面的列表,似乎涵盖了大部分的浏览器:

在ASP.NET我们添加了这些使用下面的代码片段:

Response.ClearHeaders(); 
Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1 
Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1 
Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1 
Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1 
Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1 
Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1 
Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1 
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0 
Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.0 

从实测:http://forums.asp.net/t/1013531.aspx


上述溶液从 here

+0

他说问题是服务器缓存,而不是客户端缓存。我再次看到这一点(ftp上传是可以的,ftp下载得到的是正确的文件,但http只是检索旧版本,仅用于'.js'文件) – 6502 2012-07-28 05:37:08

1

代替具有只是script标记加载的Javascript,将其加载动态

<script> 
    function loadScript(name) { 
     var s = document.createElement("script"); 
     s.src = name + "?" + (new Date).getTime(); 
     document.body.appendChild(s); 
    } 
    loadScript("script1"); 
    loadScript("script2"); 
</script>