Thursday, August 7, 2014

Website Optimization: Bundling and Minification

Intro

Website optimization is a goal of the highest order for web developers, and if it's not for you it should be. Why? Users don't like to wait. If a user waits more than a few seconds for a website, chances are good they'll go to a different website. You don't want that to happen to your websites do you? I'll assume not. If you don't like users then I suppose you do want this to happen, but I can't please everyone. Hey, just ignore the advice if that's you!

There are quite a plethora of ways to optimize websites. The server side code could be slow, the database behind it (if there is one) could be slow, internet connections can be problematic, javascript on your pages can be pokey, and you could just be forcing users to download too much stuff when they hit your site. This article concerns just a portion of the last item there, too much crap to download. Lots of things can cause your site to have a bloated download size or too many files to download; too many images, large images, uncompressed static files, server-side controls that render bloated html content to the client, too many and/or too large scripts and css files and more. Once again, this last item is what we're dealing with.

I hope you have a good sense from the above section that there can be quite a number of reasons for a slow site. Keep in mind we're covering just one of them here! If you're developing websites, I strongly encourage you to do some more research on teh interwebs to see what all else you can do to speed up your websites.

What is Bundling?

Bundling is pretty much what it sounds like; you bundle things together. In this case, I'm talking about bundling together javascript files and css files so that there are fewer hits to your server. Put on your pretending cap for a moment and picture a world where your website has just a single .js file. A user who visits your site will only download that 1 js file, so you've cut down on their outbound connections and your inbound connections. FTW! Now picture in yer noggin what that js file would look like if you have anything larger than a basic site: it would be a jumbled mess and it would be extremely difficult to find anything. That there fill will be huge! This is where bundling comes in. ASP.Net bundling lets you, with server-side code, specify group(s) of javascript or css files to bundle together at runtime. This means that you can keep them files separated (thanks Offspring!) in the development environment so your site is better organized and your code easier to manage, but your users get served much fewer file(s) when they view your page.

What is Minification

Minification is a podunk form of compression. In the web world, it means you strip js and css files down to a bare minimum of text that still functions the same. Take for example this line of js:

var myVariable = 3;

It doesn't seem like much, but this line is 19 characters long. Compare it to this line:

var m=3;

This new line is 8 characters long, and means the same thing. The variable name is different but that's it. Now going back and making all your js look like this will probably get you punched by your co-workers. Instead, let ASP.Net handle it for you! You can keep your js code looking nice and pretty on the development side, while serving your users much more compressed-looking code that works exactly the same.


Code!

Let's see how to go about using the built-in bundling and minification in .Net. Fire up VS Express and create a new ASP.Net Web Application. Mine is named blogbundlemin.
 

Pick the MVC template and change authentication to "No Authentication":


After a few seconds you should now have yourself a basic website template. Expand the scripts folder that VS made for you in your website and create a few js files. It doesn't matter what you put in them, but here is what I ended up with (zz_1.js, zz_2.js and zz_3.js):

The contents are pretty slim too:

zz_1.js:
var myVariable1 = 1234;

zz_2.js:
var myVariable2 = "purple";

zz_3.js:
var myVariable3 = "something or other";


Now open up the App_Start folder. In there is a special file that ASP.Net has already generated for you called BundleConfig.cs. Open up that file. You'll see that there's already a method in this class called RegisterBundles(), and there's some code in there already that is adding bundles. Go ahead and drop some code in there at the top of the method:

            bundles.Add(new ScriptBundle("~/bundles/local").Include(
                "~/Scripts/zz_*"));


This tells .Net to create a bundled named "~/bundles/local", and include in this bundle all the files named "~/Scripts/zz_*".

Great! Now we have a cool bundle, but how do we use it in one of the pages of our site? Open up Views/Shared/_Layout.cshtml. For those not familiar with MVC, this is like a master page from the world of web forms. Most if not all pages in the site will use this _Layout page to use a common layout and theme throughout the site. Towards the bottom of the file you can see a couple of lines that look like @Scripts.Render; add one for your own bundle. Here's what your code should look like:

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/bundles/local")
    @RenderSection("scripts", required: false)


Now run the project in Internet Explorer. Once the site finished loading, hit F12 to bring up developer tools. Now click on the weird little "network" icon on the left then click the Play button.


Now hit Ctrl-F5 to force IE to refresh all its local content for this page, then click the stop button. Your developer tools should look like this:



You can see your lovely bundle in there! If you double-click this line then click the "Response body" link you'll see what's in the bundle:


Yes that's right ladies and germs, .Net has both minified your content (it put all 3 variable declarations on one line, got rid of the trailing semicolon, and removed unnecessary whitespace)  as well as bundling all 3 files together. Nifty!

What's Next?

You can bundle css files too. It's just as easy as bundling js files. Give it a whirl!

Can you figure out how to turn on and off bundling? Hint: there are at least 2 good ways to do it.

You can also go super-bold and explore other ways to optimize websites. Heck, just play around with the IE developer tools some more if you're bored, they're fun.

Resources

ASP.Net Bundling and Minification

No comments:

Post a Comment