Sai Stuff to Developers

December 14, 2016

How to crack browser cache issue?

Filed under: Client Side Applications — tosaik @ 5:10 pm
Tags: , ,

When we access any web application, our browser hits the server and gets all the required resource/content files and cache those for further requests to avoid latency and improve performance of the application.

This browser cache will be a problem in case if there is any changes to these resource or content files at server end, and these changes should reflect whenever user visit this application for the next time. But in most of the cases the browser will check for these files in their cache. If it founds then it won’t get latest files from server and lost the latest changes at client end.

To solve this issue we need to inform the browser that there are some changes to the files (JavaScript or CSS or images) and this time pick it from the server and update in your cache. To do so we need to append some query string kind of text at the end of each file, such that every time this string changes browser/cache-system treats it as a new file and requests the server for the latest version.

Following are the different approaches can be used.

Static Approach

Whenever the files are updated, all references to the files could be manually updated to increment a version number as follows.

<script type="text/javascript" src="~/Scripts/config.js?v=1"></script>

If there is any updates now increment the version from 1 to 2 as below

<script type="text/javascript" src="~/Scripts/config.js?v=2"></script>

Note: Instead of number we can have any number or string which uniquely identifies it for example may be any hash string or GUID string.

Advantages

  • Browser will request for new file request in case there is a change in version string. If there is no change then it will get from its cache system and improves performance.

Disadvantages

  • If we forget to update or change the version string at any file then the functionality might not work as expected. This can be avoided in case we are using any bundling tools like gulp or web pack.

Dynamic Approach

In this approach, developer always appends current server date time ticks such that every time a browser treat it as a new request and always get the latest version from the server irrespective of files updated or not.

MVC:  

<script type="text/javascript" src="~/Scripts/config.js?v=@(DateTime.Now.Ticks)"></script>

Advantages

  • No need to worry of forgetting to update the version string as every time this will be changed automatically irrespective of changes or updates.

Disadvantages

  • There will be lot of performance issue as for every request client browser should request for the file(s).
  • It will use lots of bandwidth and especially on slow networks.
  • Not much utilizing the browser cache system feature.

 

Happy Coding 🙂

Blog at WordPress.com.