Whenever user access any website - images, JS and CSS
are cached by browser. But if JS and CSS are updated on server still client browser
refer the old JS and CSS. That’s very bad. It’s always good practice to provide
the latest copy of CSS and JS to client browser.
But how to do it in ASP.NET to make sure browser is
getting the updated files.
To solve this, we can use query string with JS and CSS.
For CSS, take one literal in <Head> section of
aspx page as below
<head runat="server">
<asp:Literal ID="ltStyleCss" runat="server" Text="" ></asp:Literal>
</head>
Write below code
public string CurrentVersion = "";
protected void Page_Load(object sender, EventArgs e)
{
CurrentVersion = DateTime.Today.ToString("MMddyyyy") + "_" + DateTime.Now.Hour.ToString();
ltStyleCss.Text = string.Format("<link
href=\"/ css/style.css?ver={0}\" rel=\"stylesheet\"
/>", CurrentVersion) + System.Environment.NewLine;
Here we are declaring version for each hour of the day.
You can do it for each request by specifyin current
datetime, but problem with that approach is that it affects network bandwidth.
So per hour solution is better.
It’s very easy to specify it for JS by directly passing
the version variable as query string
<script src="/Presentation/scripts/jquery.js?ver=<%=CurrentVersion%>"></script>
Pretty simple for JS but you can’t achieve the same way
for CSS. Let me know if you can do it for CSS as well.
Please leave your comments or share this tip if it’s
useful for you.