Make fewer HTTP requests: What this means and how to do it
Posted Sep 18, 2019 | 7 min. (1313 words)Thanks to advancements in JavaScript engines, the performance of websites has considerably improved in recent years. However, there are aspects of websites that are out of the control of engines and yet to be adequately optimized by browsers. One of these aspects is the number of HTTP requests that your webpage makes.
A simple way to decrease the number of HTTP requests in your page is to simplify its design. But that’s not always a practical approach. In this post, we’ll look at techniques you can employ to improve the performance of your website while still having a stylish page design.
First, why reduce HTTP requests?
Reducing HTTP requests is the most essential technique to optimize your website. This is particularly important for first-time visitors who have to download all resources instead of loading them from their browser’s cache. In fact, this is where programmers should start looking for optimizations because it has the greatest impact on the performance of websites. Plus, it can quickly be implemented.
Every script, stylesheet, image, or embedded video you add to your pages means one additional HTTP request from the user’s browser to the server. The more the browser has to make requests, the longer your page will take to fully load. That’s particularly important if your website is popular and your server has to respond to multiple simultaneous requests at the same time.
A slow website affects user experience, which in turn will result in fewer subscribers and sales.
How do I reduce the number of HTTP requests?
One of the most effective ways to reduce the number of HTTP requests is to combine all JavaScript resources into one. Similarly, it’s best to use only one stylesheet for each page. Because this process is time-consuming, most developers use a software tool such as Apache Ant for automating build processes. Alternatively, you may use an online tool such as pakd.io to make the process less painful.
To combine several files in Ant, you can use the concat
task. Keep in mind that you will need to concatenate the JavaScript files in a specific order to respect dependencies. Use a filelist
or a combination of fileset
elements to indicate the order you’d like to combine the files. Let’s look at a simple example:
<target name="js.concatenate">
<concat destfile="${bld.dir}/result.js">
<filelist dir="${src.dir}"
files="script1.js, script2.js"/>
<fileset dir="${src.dir}"
includes=".js"
excludes="script1.js, script2.js"/>
</concat>
</target>
This code tells Ant to create a file named result.js
in the bld
directory. This file will contain the result of the concatenation of script1.js
, followed by script2.js
, and followed by all files in the src directory in alphabetical order.
To avoid any conflict in the combined JavaScript files, make sure that each file ends with either a semicolon or a line terminator. You can also use the fixlastline
attribute to instruct Ant to automatically append a new line to each file if it doesn’t end in a new line, like this:
<concat destfile="${bld.dir}/result.js" fixlastline="yes">
...
</concat>
CSS Sprites
Generally, websites store images in individual files. When a browser loads a webpage, it has to make an HTTP request for each image, which slows down the overall time it takes to completely load the page. CSS sprites is a technique to combine several images into a single image called a sprite sheet.
Rather than downloading each image separately, the browser downloads a single image. It then displays the desired image segment by CSS background-image
and background-position
properties. This technique is commonly used for images that are related or are variations of the same image.
Here’s what Amazon’s sprite sheet looks like:
Clearly, the result of combining multiple images is one larger file. However, the benefits usually outweigh the cost of having to request multiple files. There are several online tools, such as Cssspritestool and Spritegen, that allow you to easily combine multiple images into a single file.
You may also use a task runner like Grunt. Grunt’s grunt-spritesmith enables you to automatically convert your images into a sprite sheet and corresponding CSS variables.
A data URL provides a way to embed data inline in webpages. More precisely, it allows you to get the contents of a file as a base64-encoded string and directly embed it in your HTML or CSS document. This will help reduce your HTTP requests because the browser doesn’t have to make a separate request to get the file.
The syntax of the data URL is as follows:
data:[<mediatype>][;base64],<data>
The mediatype
should be a MIME type string, which indicates the type of data you want to embed. For example, to embed an image, you should use image/jpeg
. And to embed an MP3 audio file, you should use audio/mpeg
.
A list of common MIME types is available on MDN.
The next component should be a base64-encoded string that is separated from mediatype
by a semicolon. The string represents the data in ASCII format using the base64 scheme for binary-to-text encoding. To obtain the base64 representation of your images, you can use the online tool provided by WebSemantics.
As an example, here’s how an image can be embedded in a webpage using the data URL scheme:
<img width="8" height="8" alt="star" src="data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7" />
This img
tag uses a data URL as the value of its src
attribute to embed the file data directly within the HTML. Therefore, no HTTP request is made to fetch the resource. The browser automatically decodes the data and constructs the file. As a result, the embedded media will look as if it was an external resource.
Keep in mind that this will increase the size of your HTML document. This is why developers often combine inline images into their stylesheets, which can be cached. For example:
div {
background:
url(data:image/gif;base64,R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp3WOyDZu6QdvCchPGolfO0o/XBs/fNwfjZ0frl3/zy7////wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5BAkAABAALAAAAAAQABAAAAVVICSOZGlCQAosJ6mu7fiyZeKqNKToQGDsM8hBADgUXoGAiqhSvp5QAnQKGIgUhwFUYLCVDFCrKUE1lBavAViFIDlTImbKC5Gm2hB0SlBCBMQiB0UjIQA7)
no-repeat
top;
padding: 10px;
}
GZip compression is also very effective in reducing the file size. If you’re using a server-side programming language like PHP, you could create data URLs automatically like this:
<?php
echo base64_encode(file_get_contents("../images/myImage.png"))
?>
If you’re using a stylesheet authoring framework, chances are it comes with helpers that simplify the process of converting your files to data URLs. Compass, for example, provides the inline-image()
helper that allows you to easily embed the contents of an image in your stylesheet. Here’s the syntax:
inline-image($image, $mime-type)
Compass also provides a separate helper for embedding fonts. The syntax is as follows:
inline-font-files([$font, $format]*)
Make fewer HTTP requests in WordPress
If you’re using a content management system such as WordPress and feel that your website is slow, the most likely culprits are plugins. Each plugin often adds its own scripts, which means more HTTP requests. As a result, it’s best to uninstall non-essential plugins and deactivate those that you only use every so often. You may also use one of the many performance plugins available on wordpress.org. Look for plugins that are designed to cut down the number of HTTP requests required to render the page.
Monitoring the performance of your web and mobile apps
In this post, we’ve taken a good look at several ways to reduce the number of HTTP requests. Still, to assess the performance impact of these changes, you’ll need a performance monitoring system in place.
A good performance monitoring system like Raygun allows you to detect, diagnose, and resolve issues that are affecting end users. It will also enable you to see what your users see in the browser and discover why they had poor quality experiences.
The screenshot above shows how Real User Monitoring surfaces individual requests and how they are affecting users on the front end. The screenshot below shows how Raygun Application Performance Monitoring (APM) surfaces the requests and their timings on the server-side.
Conclusion
As described by YUI team, about 40–60% of daily visitors to a website are first-time visitors with an empty cache. Therefore, why you should reduce your HTTP requests is obvious—optimizing your webpages for new visitors is key to more subscribers and more sales.