How to handle scripts bundling and minification in Umbraco CMS
Introduction
There are many ways to make your Umbraco website load faster.
In this article, I’ll cover the bundling and minification technique in Umbraco using native Microsoft.AspNet.Web.Optimization library to show how to optimize scripts.
Before we start make sure you’ve read my previous post on – How to handle bundling and minification in ASP .NET. You should follow the same steps:
- Install Microsoft.AspNet.Web.Optimization package
- Create BundleConfig.cs class
- Prepare js/css bundles inside BundleConfig.cs
- Force optimization
- Wire up bundling with Umbraco (register the bundling engine at application startup)
Once you go through these steps, you will be able to use bundling and minification helpers in Views and render optimized scripts.
How to register bundles in Umbraco?
The best way is to use the Umbraco Composing technique – there is a great tutorial here.
First, let’s create a folder for a new component called Compose.
Then, inside you need to create a class called (for instance) BundleComponent with Initialize() method.
This great place to wire BundleConfig during application startup:
BundleConfig.RegisterBundles(BundleTable.Bundles);
The full component looks as follows:
public class BundleComponent : IComponent
{
public void Initialize()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
public void Terminate()
{
}
}
Additionally, you can add a logger via Dependency injection (Umbraco.Core.Logging) and log the message when the bundling event was fired.
public class BundleComponent : IComponent
{
private readonly ILogger _logger;
public BundleComponent(ILogger logger)
{
_logger = logger;
}
public void Initialize()
{
BundleConfig.RegisterBundles(BundleTable.Bundles);
_logger.Info<BundleComponent>("Registering bundles");
}
public void Terminate()
{
}
}
In the end, good luck to you, and Happy Umbraco bundling & minification 😀