The latest Telerik MVC set of components features a ScriptRegistrar component that’s responsible for compressing or combining scripts into a single file.  This compression utility is very easy to implement: to setup this component, use the following steps:

1. In your configuration file, add the following line to the httpHandlers element in <system.web> and <system.webserver>:

<add verb=GET,HEAD path=asset.axd validate=false type=Telerik.Web.Mvc.WebAssetHttpHandler, Telerik.Web.Mvc/>

2. Use the ScriptRegistrar and groups to group scripts together.  Preferrably, put this in the master page at the very end of the page before the ending </body> tag.

<% Html.Telerik().ScriptRegistrar().Scripts((s) =>
{
    s.AddGroup(“MyGroup”, (g) =>
    {
         g.Add(“script1.js”).Add(“script2.js”).Add(“script3.js”);
    }
}).Render(); %>

Now we have our scripts defined, but if you run the app, you will be disappointed by finding out three script files were added.  Instead, we need to add some additional properties to the group definition.

s.AddGroup(“MyGroup”, (g) =>
{
     g.Add(“script1.js”).Add(“script2.js”).Add(“script3.js”).Combined(true).Compress(true).CacheDurationInDays(10);
}

The Combined() method signals to combine all three scripts together within this group  The Compress() method signals to compress the scripts, and the CacheDurationInDays method specifies the number of days to cache the scripts.

This can also be performed by stylesheets, without the ability to combine and compress them.  You can group them together using the same approach, except using the StyleSheets method.

This setup produces the following output.

<script type=”text/javascript” src=”/asset.axd?id=mwAAAB-LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee–997o7nU4n99__P1xmZAFs9s5K2smeIYCqyB8_fnwfPyJ-8UfT9qNHH2WrVVlMs7aolnffbf90dpk107pYtR-NPrqkr_d2dh6O7413d3fujXfos-lHj9p6ndMvs48e3fv0_ugj-vm9X_zRitqeVMs2X7Z3XzOAhlqf83fVR492Rh8tqcVFXa1Xu-Ofbj76JSP-fNf7fI8___4v-f4v-X8AJmOKf5sAAAA%3d”></script>

 

<link type=”text/css” href=”/asset.axd?id=kwAAAB-LCAAAAAAABADtvQdgHEmWJSYvbcp7f0r1StfgdKEIgGATJNiQQBDswYjN5pLsHWlHIymrKoHKZVZlXWYWQMztnbz33nvvvffee–997o7nU4n99__P1xmZAFs9s5K2smeIYCqyB8_fnwfPyJ-8UfT9qNHH7X5u_butGk-Gn10SX_u7ew8HN8b7-7u3Bvv0GfTjx619TqnX2YfPbr36f3RR_Tze7_4oxW1PamWbb5s757w2-f8efXRo53RR0v69nXR5mMA_iUj_nhXPm7zMq-Lt-Pq_LyY5tTdA2n0_V_y_V_y_wCso4bJkwAAAA%3d%3d” rel=”stylesheet”/>

The other option for adding scripts is to use the DefaultGroup method, a method that uses the default group to setup scripts for.  For instance, we setup a custom group, but if you only need one group, we can use the DefaultGroup method to define all our scripts in.