Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you pre-cache ASP.NET Bundles?

Every time I deploy an MVC web application my server has to re-cache all js and css bundles.

Because of this it can take several seconds for the first view to render after deploying.

Is there a way to pre-cache bundles? After all, the files are static at compile time.

like image 624
Mark Rucker Avatar asked Jul 15 '13 20:07

Mark Rucker


People also ask

What is difference between bundling and minification?

Both bundling and minification are the two separate techniques to reduce the load time. The bundling reduces the number of requests to the Server, while the minification reduces the size of the requested assets.

Where does ASP.NET store cached data?

Cache is stored in web server memory.

How minification is implemented in MVC?

Bundling and minification can be enabled or disabled in two ways: either setting the value of the debug attribute in the compilation Element in the Web. config file or setting the enableOptimizations property on the BundleTable class. In the following example, debug is set to true in web.

What is the use of BundleConfig in MVC?

To improve the performance of the application, ASP.NET MVC provides inbuilt feature to bundle multiple files into a single, file which in turn improves the page load performance because of fewer HTTP requests.


1 Answers

Solution

To fix we replaced the default memory cache with caching that persisted beyond the App Pool life.

To do this we inherited from ScriptBundle and overrode CacheLookup() and UpdateCache().

/// <summary>
/// override cache functionality in ScriptBundle to use 
/// persistent cache instead of HttpContext.Current.Cache
/// </summary>
public class ScriptBundleUsingPersistentCaching : ScriptBundle
{
    public ScriptBundleUsingPersistentCaching(string virtualPath)
        : base(virtualPath)
    { }

    public ScriptBundleUsingPersistentCaching(string virtualPath, string cdnPath)
        : base(virtualPath, cdnPath)
    { }

    public override BundleResponse CacheLookup(BundleContext context)
    {
        //custom cache read
    }

    public override void UpdateCache(BundleContext context, BundleResponse response)
    {
        //custom cache save
    }
}

Complications

The only other wrench worth noting had to do with our persistent caching tool. In order to cache we had to have a serializable object. Unfortunately, BundleResponse is not marked as Serializable.

Our solution was to create a small utility class to deconstruct BundleResponse into its value types. Once we did this we were able to serialize the utility class. Then, when retrieving from the cache, we reconstruct the BundleResponse.

like image 171
Mark Rucker Avatar answered Sep 28 '22 04:09

Mark Rucker