Sunday, October 5, 2014

Combine AngularJS templates in ASP.NET MVC app

Lots of people write pretty heavy JavaScript applications these days, which normally involves client side templates rendering. When we have a lot of templates it potentially might slow down initial application load. AngularJS application lazy loads external files through ajax requests and caches them in $templateCache service in order to reuse them later. One of the possible solutions on how to improve initial load time is to combine multiple files and serve them as one single dependency.

I tried to do it in ASP.NET MVC application recently, but haven’t found any good solutions. There are some nice grunt tasks (for example grunt-angular-templates) to combine AngularJS templates, but I didn’t want to introduce nodejs dependency and implemented an ASP.NET MVC bundle that does pretty much the same thing. Maybe in the next version of Visual Studio grunt/gulp integration is going to be first class citizen, but not for now.

So I created a NuGet package AngularTemplates.Compile that contains ASP.NET MVC bundle and MsBuild task (in case you want to use it outside of ASP.NET MVC pipeline) to combine multiple AngularJS templates. First things first add this package:

PM> Install-Package AngularTemplates.Compile

Then add a bundle with templates:

And render this bundle in your view:

The output result will look similar to this:

Please note that it will generate combined result only when bundle optimizations are enabled (BundleTable.EnableOptimizations = true, or "debug" attribute of "compilation" section in web.config is set to false).

If you prefer MsBuild to precompile and bundle templates/javascripts - there is also available a task:

Packages source are available on github: