Home
Do you bundle and minify your JavaScript?
  v3.0 Posted at 2/11/2012 6:10 PM by Adam Stephensen

Did you know you can improve the speed of your MVC app by using a built in feature called bundling and minification.

Bundling allows you to:

  1. Specify the JavaScript files you want to include in your app and the order in which they are loaded
  2. Put them into one JavaScript file reducing calls to the server.

The next part of the process is minification. This means that all the whitespace is removed from the JavaScript files and long variables names are shortened where possible to decrease the size of the package.
All this adds up to a faster MVC app and a better user experience.

Layout.cshtml

<script type="text/javascript" src="/SoftwareDevelopment/RulesToBetterMVC/Pages/@Url.Content("></script>
<script type="text/javascript" src="/SoftwareDevelopment/RulesToBetterMVC/Pages/@Url.Content("></script>
<script type="text/javascript" src="/SoftwareDevelopment/RulesToBetterMVC/Pages/@Url.Content("></script>
<script type="text/javascript" src="/SoftwareDevelopment/RulesToBetterMVC/Pages/@Url.Content("></script>
<script type="text/javascript" src="/SoftwareDevelopment/RulesToBetterMVC/Pages/@Url.Content("></script>
<script type="text/javascript" src="/SoftwareDevelopment/RulesToBetterMVC/Pages/@Url.Content("></script>
Figure: Scripts are specified in the view

BundleConfig.cs

public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/SSW").Include(
"~/Scripts/2011.3.1115/jquery-1.6.4.min.js",
"~/Scripts/jquery-ui-1.8.16.min.js",
"~/Scripts/jquery.formatCurrency-1.4.0.min.js",
"~/Scripts/date.js",
"~/Scripts/jquery.watermark.min.js",
"~/Scripts/jquery.cross-slide.min.js"));
}

Layout.cshtml

@Scripts.Render("~/bundles/ssw")
Figure: A bundle is created in the bundle config and then referenced in the view

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments: