Tuesday, April 21, 2015

Defining and using Server variables in the html head section of page

My browser was caching the javasscripts and css and it gets annoying when you are multiple design changes to code. So I decided to do cache busting. I defined a Random number variable in code behind and wanted to use it in html <head> so that every time a request is made, the browser takes it as a new request to the server with a fresh copy of styles and javascript files. The solution is a little quirky, but works:

     <link href="mystyle.css?rn=<%="" +Rand %>" type="text/css" rel="stylesheet"/>

where:
rn : is variable for Random Number
Rand : is server side generated Random number

Considering the Random number generated as 1234, the output would be like below:

     <link href="mystyle.css?rn=1234" type="text/css" rel="stylesheet"/>


Note: Use this for development only. Caching is always good to have in production to speed up loading times. With any new build of css/javascript, a version number can be assigned to get a fresh copy.