ASP.NET MVC > Bundles

Optimize JavaScript and CSS file in ASP.NET MVC

How to optimize JavaScript and CSS file in ASP.NET MVC?


There are many ways through which script and css files added via ScriptBundle and StyleBundle can be optimized.

The first and better way of optimizing JavaScript and CSS files are by change the compilation settings in root web.config file.

Let’s take an example of the Bundle created for .css files

~/APP_START/BUNDLECONFIG.CS

bundles.Add(new StyleBundle("~/Content/css").Include(
          "~/Content/bootstrap.css",
          "~/Content/site.css"));

When above bundle is called in the Layout or View page like below

VIEW PAGE

@Styles.Render("~/Content/css")

It renders following link tag in the browser source

BROWSER SOURCE CODE

<link href="/Content/bootstrap.css" rel="stylesheet"/>
   <link href="/Content/site.css" rel="stylesheet"/>

But when the compilation debug mode is set to false in the root web.config file

~/WEB.CONFIG FILE

<compilation debug="false" targetFramework="4.5" />

OR, the optimization setting can be enabled by setting below setting in BundleConfig.cs

~/APP_START/BUNDLECONFIG.CS

BundleTable.EnableOptimizations = true;

The same style renders like below in browser source

BROWSER SOURCE CODE

<link href="/Content/css?v=MDbdFKJHBa_ctS5x4He1bMV0_RjRq8jpcIAvPpKiN6U1" rel="stylesheet"/>

Now what is the difference?

The difference between the output of debug true and false in web.config file setting is following

  1. The comments, spaces, code alignments etc. have been removed
  2. Both files bootstrap.css and site.css have been combined into one file.
  3. Instead of rendering two <link> tags, the combined file has been rendered only with one link tag.
What is the benefit?

The benefit of doing this are following
  1. Because, the comments, spaces, code alignments have been removed so the file size will become very less
  2. Now, instead of two <link> tag, only one <link> tag is rendered in the browser so only one request goes to the server and both combined files are loaded in the browser
  3. As a result, the speed of downloading the same content from both files and now with only one combined file will be much better and it will overall increase the performance of the web page.
 Views: 9645 | Post Order: 120



Write for us






Hosting Recommendations