Sunday, 29 March 2015

While writing my website I have read many blog posts how to do this the best way.

Couple targets I had in mind

  • Create bundle that will create smaller file to download
  • Almost everyone is using cdn, unless they are living behind firewall
  • And if cdn fails, provide file from local source

Key points:
  • Bundling is simply getting multiple files under one.
  • Minification is making files smaller
In my example I have java script files.

To render the bundle i need script in my page such as

 @Scripts.Render("~/bundles/jquery")

How to create a bundle


In your ASP.NET application you will have to find file: BundleConfig.cs
inside you will be able to find default setup, which might not be used in your template. 

     bundles.Add(new ScriptBundle("~/bundles/jquery")
                .Include("~/Scripts/jquery-{version}.js")); 

You might need to enable optimizations with code

 BundleTable.EnableOptimizations = true;
in order to see the efect on your page once run it.
   

Now to CDN


  1. content delivery network (CDN) is a system of distributed servers (network) that deliver webpages and other Web content to a user based on the geographic locations of the user, the origin of the webpage and a content delivery server.

Is supposed to offload some of the traffic, but what if I cannot access it?

We can create backup configuration, so I a case that cdn is unreachable we do not get down with our application.

How to achieve it?
First we need to tell bundle configuration that we are going to use cdn
  bundles.UseCdn = true;
And then we need to provide code with cdn first
  bundles.Add(new ScriptBundle("~/bundles/jquery", "https://code.jquery.com/jquery-{version}.min.js")
                .Include("~/Scripts/jquery-{version}.min.js"));
Notice the include after the path to cdn. This defacto says if you cannot get the file from here look to this alternative location

Example of the code is here:

One of many sources:
http://www.asp.net/mvc/overview/performance/bundling-and-minification
www.stackoverflow.com