Introduction
Many times, we faced "CSS is not applied in latest version at client's or user's browser" problem. As a solution (as many developers are aware), just append the version number with query string in CSS file reference mentioned in link tag. I had the same problem and I applied it. Now the next problem is, every time I have to remember to change in version number in case of any change in CSS. Why remember it if we can add dynamic version value in query string.
Using the Code
To add version number dynamically in query string, I tried this way as we do normally.
<link href="/styles/default.css?v=<%=AppVerNum %>" rel="stylesheet" type="text/css" />
Check the above link
tag where AppVerNum
is the server side variable. To assign value of this variable, we can write any server side code, so no need to change version number every time. Is your problem resolved? Yes, but partially and big NO after that because this time again you have changed the query string value, but really it will write AppVerNum
value at client side? Check your browser source code how this link tag would be rendered. It will look like below:
<link href="/styles/default.css?v=<%=AppVerNum %>" rel="stylesheet" type="text/css" />
Your query string value is now <%=AppVerNum, so it will render the latest CSS in to browser, but problem will be there again if change would be there in css. So how to get the AppVerNum
value in link tag. Check the below code:
<link href="/styles/default.css?v=<%="" + AppVerNum %>" rel="stylesheet" type="text/css" />
Now check link tag in browser source code. Your problem is resolved.
<link href="/styles/default.css?v=121" rel="stylesheet" type="text/css" />
Here 121 is the dynamic value generated for
AppVerNum
from server side code. Remember that the value of this variable should not be dynamic on every request, it should single per release.
Points of Interest
We assume many times, it will and should work. But sometimes, it is different than what we thought. This is the example of it.