Jan 13, 2012

IE CSS/JS caching issue and how to fix

This is interesting hack:

On IE (and IE-compatible browser: Avant Browser / Maxthon…etc), JS and CSS can be cached and not loaded when you want.

For e.g: you have 2 different global.css files to use before and after user login (don’t ask me why) . In your index.htm you may load your CSS:

<link href="/Styles/global.css" rel="stylesheet" type="text/css"/> //issue goes here

global.css <<before login>>
#header { color: #ccc; }

global.css <<after login>>
#header { color: #fff}

Now if you login, the #header color is still #ccc !

Root cause: IE cached files and do not refresh the global.css. On Chrome/FF, the browser is able to detect changes and reload your new global.css

Solution: add in a dynamic query string to let browser know there is a change in the path (URL specific). Browser will reload the CSS for you

<link href="/Styles/global.css?v=<%= DateTime.Now();%>" rel="stylesheet" type="text/css"/> //issue go away

That’s it ! The dynamic link will force browser to reload CSS /JS every time.

Notes: Only use it for files that are frequently changed, otherwise you’ll reduce performance.

No comments:

Post a Comment