When you are building AngularJS apps you will probably want to store all your various controllers, directives, filters, etc. into different files to keep it all nicely separated and easy to manage. However, putting script blocks to all those files in your HTML is not efficient in the least. Not only do you have several round-trips to the server, the browser will be downloading a lot of code that is designed to be readable and maintainable, potentially with lots of additional whitespace and comments.
public static void RegisterBundles(BundleCollection bundles)
// Configure the Angular Application
// The services
This method is called from the
Application_Start() method in global.asax.cs.
In the layout or view you can then reference these bundles using the path passed in to the constructor. Like this:
<!-- Other bits go here -->
Remember to use the tilde notation just like in the code that defines the bundles.
When the optimisations are turned off the scripts will render as a script block per include. When the optimisations are turned on then it outputs one script block. When the server receives a request for that script it resolves the name to match the bundle, it then sends back an amalgamated and minified version of that script file. This then loads much faster on the client as there are less roundtrips to the server and takes much less bandwidth.
Here’s what the two scenarios look like:
Optimisations turned off
This is what the two
@Script.Render() blocks at the end of the HTML look like:
And when this is rendered in the browser, the following calls are made.
There are 18 requests in the above example. 901kb is transferred to the browser and it took 911ms to complete loading everything (the above does not show images, css or ajax calls that are also downloaded as part of the page)
Optimisations turned on
Now, compare the above to this representation of the same section of the page:
And when rendered in the browser, it makes the following requests:
There are now just two requests, one for the base-framework bundle, and one for the angular-catalogue (our application code) bundle.
Because the bundling process minifies the files the amount of data transferred is much smaller too, in this case 223kb (a saving of 678kb or roughly 75%). For established frameworks that ship with a *.min.js version the bundling framework will use that convention and use the existing minified file. If it can’t find one it will minify the file for you.
And because there is less data to transfer and less network round-trips to wait for the time to fully load the page has been reduced to 618ms (a saving of 293ms or roughly ⅔ of the time of the previous request).
There is a lot more to bundling than I’ve mentioned here. For a more in depth view of bundling read Scott Guthrie’s blog on Bundling and Minification Support.