The below code will help us to implement cache to render CSS and JS files in MVC C# and also to improve the performance of page loading.
The following steps:
- 1)
Added a Cache Helper class to
Cache file,
- 2) Import the Utility on cshtml file
- 3) Apply the CacheHelper.CacheFile() for each js and css file on views
- 4) Result
For Example,> Added a Cache Helper class to Cache file,
using System;
using System.IO;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;
namespace Utility
{
public static class CacheHelper
{
public static string CacheFile(string rootRelativePath)
{
if (HttpRuntime.Cache[rootRelativePath] == null)
{
string absolute =
HostingEnvironment.MapPath(rootRelativePath);
DateTime date = File.GetLastWriteTime(absolute);
string result = rootRelativePath + "?v=" + date.Ticks;
HttpRuntime.Cache.Insert(rootRelativePath, result, new CacheDependency(absolute));
}
return HttpRuntime.Cache[rootRelativePath] as string;
}
}
}
Import the Utility on cshtml file & Apply the CacheHelper.CacheFile()
import helper class > @using Utility
CSS file,
<link href="@CacheHeper.CacheFile("/includes/css/bootstrap.min.css")" rel="stylesheet" />
JS file,
<script src="@CacheHeper.CacheFile("/Scripts/jquery-maskedinput.js")"></script>