Great website performance is a key part of good user experience. Pages should load and display quickly in order not to leave the user waiting and staring at their browser's loading indicator or a blank page.
The time required to render a web page mainly depends on four factors:
- Network latency
- Available bandwidth
- Number of HTTP requests
- Size of HTTP requests
While we usually don't have any impact on network latency or bandwidth available to the user, we certainly do have an impact on the number and size of HTTP requests made by our web page. Our goal is to minimize both to improve performance.
Bundling: Combining Assets Together
Most browsers only allow a limited number of connections to each host at the same time. Usually, this number is around 6. This means that loading many small assets usually isn't done all in parallel. Instead, those requests are made in sequential batches. (You can compare this process to boiling eggs in a small pot which can only hold 6 eggs at the same time: To boil 30 eggs, you'll have to boil them in 5 batches of 6.)
That's what bundling helps with: It reduces the number of necessary HTTP requests by merging multiple stylesheet or script files into a single file that can be loaded at once.
Here's an example: If you have a web page referencing 10 stylesheets and 25 scripts files, you'd usually have to request 36 (1 + 10 + 25) individual files. That'll take some time! With bundling, that numbers goes down to 3 (1 page, 1 stylesheet bundle, and 1 script bundle), which can be done in parallel.
If you open the Chrome Developer Tools (or whichever browser developer tools you prefer), you can clearly see the difference bundling makes. First, the unbundled assets:
In comparison, these are the bundled versions:
Rather than making 10 additional HTTP requests, the
index.html now only requests 2 assets, one stylesheet and one script bundle.
Minification: Reducing Request Size
To reduce the size of HTTP requests, we can use minification to shorten a file's contents without changing its meaning. That mainly includes removing superfluous whitespace characters and code comments, like in the following example:
/* Make text all-uppercase */
Here's the minified version of the above CSS rule. It's about 58% percent smaller, but will be treated exactly the same by browsers:
Note that the whitespace is gone, as is the comment and the final semicolon. Also, the hex color value has been shortened, but still describes the same color. To see a real-world example of CSS bundling, check out the stylesheet bundle of this very blog.
For a thorough introduction to bundling and minification, check out this Bundling and Minification guide. It includes some helpful visualizations of the bottlenecks that can occur when loading a web page.