Tuesday 2 January 2018

Forcing Browsers to Fetch js/css Files From Server Instead of Cache

Sometimes we have to make some changes in our css or js files. After this we upload it to our servers. But while opening our pages in browser, it wont reflect our changes. We may have to clear our browser cache to see that changes. This is not a feasible solution for websites with thousands of visitors. So here is simple tip we can use in our websites.

First declare a global application variable in our global.asax file

void Application_BeginRequest(Object source, EventArgs e)  
{  
    Application["version"] = "1.0";  


Now while including js/css files in our aspx pages, just add a query string with them as follows.

<script src="youjsfilename.js?ver=<%= Application["version"] %>" type="text/javascript"></script>  
   <link href="youcssfilename.css?ver=<%= Application["version"] %>" rel="stylesheet"  
       type="text/css" /> 
        
Now whenever you make changes in these files, you can just change the value of "version" in global file.

void Application_BeginRequest(Object source, EventArgs e)  
{  
    Application["version"] = "1.1";  
}  

Hope this will be helpful!

No comments:

Post a Comment