Bundling is a feature in .NET that allows us to combine or bundle multiple files into a single file. We do bundle files to improve performance of a site. Fewer files also means less HTTP requests which means faster performance. To use bundling in Sitecore MVC you are going to have to implement a custom pipeline. So, without further due here we go.
RegisterBundles pipeline
In this custom pipeline we setup our bundles.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Optimization;
using Sitecore;
using Sitecore.Pipelines;
namespace Local.Sitecore.Website.Pipelines.Loader
{
public class RegisterBundles
{
[UsedImplicitly]
public virtual void Process(PipelineArgs args)
{
Register(BundleTable.Bundles);
}
private void Register(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/js").Include(
"~/includes/js/jquery-core.js",
"~/includes/js/plugins/jquery-plugins.js",
"~/includes/js/plugins/jquery.cycle.all.min.js"
));
bundles.Add(new StyleBundle("~/bundles/css").IncludeDirectory(
"~/includes/css", "*.css"
));
}
}
}
Configure pipeline
Let's register our pipeline and add "bundles" to the IgnoreUrlPrefixes setting.
<?xml version="1.0"?>
<configuration xmlns:patch="http://local.sitecore.net/xmlconfig" xmlns:set="http://local.sitecore.net/xmlconfig/set/">
<sitecore>
<pipelines>
<initialize>
<processor patch:before="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeGlobalFilters, Sitecore.Mvc']"
type="Local.Sitecore.Website.Pipelines.Loader.RegisterBundles, Local.Sitecore.Website" />
</initialize>
</pipelines>
<settings>
<setting name="IgnoreUrlPrefixes" value="/sitecore/default.aspx|/trace.axd|/webresource.axd|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.DialogHandler.aspx|/sitecore/shell/applications/content manager/telerik.web.ui.dialoghandler.aspx|/sitecore/shell/Controls/Rich Text Editor/Telerik.Web.UI.SpellCheckHandler.axd|/Telerik.Web.UI.WebResource.axd|/sitecore/admin/upgrade/|/layouts/testing|/sitecore/service/xdb/disabled.aspx|/bundles" />
</settings>
</sitecore>
</configuration>
Layout
And this is how we use bundling in the layout.
@using Sitecore.Mvc
@using System.Web.Optimization
<!DOCTYPE html>
<html>
<head>
<title>Bundle me in Sitecore MVC</title>
@Styles.Render("~/bundles/css")
@Scripts.Render("~/bundles/js")
</head>
<body>
@Html.Sitecore().Placeholder("main")
</body>
</html>
That's all for today. Keeping it simple :)