To have better user experience and improve website's performance, modern browsers used to cache the static files like css, js and images. While it helps your website to perform better but it could also lead to serve stale files. If you have made any changes to your css, js or image files, the browsers will keep showing the old images until it refreshes it cache. Sometimes the users have to do a full refresh (Ctrl + F5 or Ctrl + R) for the browser to get latest or fresh content of these files.
In this case we need to tell the browser to get the new files from server to make sure that the user will always be served with latest files without doing full refresh on the browser.
Some ways to acheive this behavior could be:
- Every time you make any changes in the file content, also change the file name and its references.
- Another way is to add a random string behind the js, css or image url.
Here we will use the second approach to add a random string for these files urls.
The good news is that ASP.NET Core has in-build feature for this issue. We can use the tag helper:
asp-append-version="true"
To enable this feature ON for particualr static file, we just need to add the above asp-append-version
tag-helper/attribute as below.
CSS <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> JS <script src="~/js/site.js" asp-append-version="true"></script> Image <img src="~/images/logo.png" asp-append-version="true" />
After making these changes you can check the rendered html from browser source code or inspect element using browser's developer tools. It will be found that there is a random string attached behind file name.
If you make any change within the file content for css/js etc, when the next time browser will render it, it will fetch the fresh file from server because of different random string attached to the file URL.
CSS https://localhost:7163/css/site.css?v=1Ip96t8Xk8GevF37Kz0Wu_1tuNyEZJcH5PYrmiK1fNs JS https://localhost:7163/js/site.js?v=mC13cRUFjf1YiinDRFWfv-eOXac88lLptssglYLhYtQ
You will see a different random string appended each time the changes are made to the file cotent, which makes sure that the browser will fetch the latest copy from server.
No comments:
Post a Comment