How to create a browser cache save URL to a javascript or css file in SharePoint

on Monday, March 29, 2010

How to create a browser cache save URL to a javascript or css file in SharePoint

Often it is necessary to ensure that updates to files on the server get populated to the client asap. Especially when it comes to dependencies to custom javascript of CSS files and server controls.

SharePoint itself does this by adding a query string to some of its vital Javascript files. E.g.:

/_layouts/1033/core.js?rev=PQia%2B0EyudqxiQyTfOSR%2Fw%3D%3D

Whenever the core.js file changes on the server a new query string value is generated. That allows browsers to cache the file as long as the file does not change on the server.


Today I got the question if it is possible to utilize the same method for custom js and css files. The answer is yes.

SharePoint provides the functionality to generate browser cache save Urls for such files if they reside inside the _layouts directory or one of it's localized subdirectory using the following method:


public static string Microsoft.SharePoint.Utilities.SPUtility.MakeBrowserCacheSafeLayoutsUrl(string name, bool localizable)


The first parameter needs to be the filename without a path (e.g. test.css) the second defines if the file resides in a language specific subdirectory or directly in the _layouts directory.


The following code will (e.g.) create the output below for german locale:


string saveUrl = Microsoft.SharePoint.Utilities.SPUtility.MakeBrowserCacheSafeLayoutsUrl("my-own.js", true);


/_layouts/1031/my-own.js?rev=PQia%2B0EyudqxiQyTfOSR%2Fw%3D%3D

1 comments:

RenewSSLs said...

Thanks for sharing the information. That’s a awesome article you posted. I found the post very useful as well as interesting. I will come back to read some more.
Renew SSL