Wednesday, April 25, 2012

Avoiding JavaScript and CSS stylesheet caching problems in sharepoint

Good news - Our application got new branding in this release, which changed my perception as a developer to see SharePoint applications. SharePoint is not only about C# and CAML other things like JS, CSS and HTML also plays major role in your application.

We mainly work on the business logic of the application but this time got chance to work with UI designers, and Changing look and feel of SharePoint is not a easy task as lots of tweaking is needed to overwrite existing styles dynamically applied by the SharePoint.

So let me introduce you the structure of our application, All JS, Stylesheets and images are placed inside the _layouts [14 hive\Layouts] folder. 
UI designer made some changes to apply branding on homepage and gave update files to me. I have merged all the files properly and deployed the application on the server. but changes are not reflected and UI is breaking. Called my fellow UI designer showed the issue. She performed hard refresh (CTRL + F5) this resolved all the issues. 
Root cause is the Browser caching for js and css files.
This raised another question in my mind I can perform hard refresh but in Production we cannot tell every user to perform hard refresh.

So here is the solution to above problem...
To avoid browser caching a file even after it is updated, simple change the linking URL format

<link href="/_LAYOUTS/ProjectName/mystyles.css" rel="stylesheet" type="text/css">link>
<script src="/_LAYOUTS/ProjectName/myscript.js" type="text/javascript"> script>


<link href="/_LAYOUTS/ProjectName/mystyles.css?rev=<build-version>" rel="stylesheet" type="text/css">link>
<script src="/_LAYOUTS/ProjectName/myscript.js?rev=<random number>" type="text/javascript"> script>

Update this numbers whenever your file is updated, to avoid facing the same issue of not seeing updated CSS and JavaScript files by default.


  1. Good one... SharePoint CSS indeed causes a hell lot of work

  2. Got to learn something new today.....
    Thanx for the post

  3. The information in your post about SharePoint is more interesting. and this info is more useful for the developers to develop the SharePoint apps. Thanks for share this valuable info

  4. More useful information..Thanks for the Post.

  5. Chetan C G
    Do we need to pass the key also or only value can be used
    e.g /_LAYOUTS/ProjectName/mystyles.css?455456

  6. That is an extremely smart written article. I will be sure to bookmark it and return to learn extra of your useful information. Thank you for the post. I will certainly return.