Site icon Treehouse Blog

How Data URIs Speed Improve Website Speed

Using Data URIs to Speed Up Your Website

Using Data URIs to Speed Up Your Website

As our websites grow more complex, web performance is becoming an increasingly important topic. There are many different strategies that you can employ to improve the performance of your websites. These include optimising images, combining multiple CSS files, or setting appropriate caching headers so that the browser doesn’t have to download resources multiple times if they haven’t changed.

Free trial on Treehouse: Do you want to improve your development skills? Click here to try a free trial on Treehouse.

In this blog post, you’re going to learn about data URIs, and how you can use them to increase the performance of your websites.

Let’s get started.

What Is a Data URI?

A data URI is a base64 encoded string that represents a file. Getting the contents of a file as a string means that you can directly embed the data within your HTML or CSS code. When the browser encounters a data URI in your code, it’s able to decode the data and construct the original file.

You can use data URIs for all sorts of different file types, but they’re most commonly used on the web for images (and sometimes fonts).

A data URI follows a certain scheme (as shown below) that includes some information about the encoded file — such as the mime type — along with the encoded data itself.

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

You can use a data URI within your HTML or CSS code wherever you would have placed a file path before. For example you could use a data URI to specify a background image in CSS:

li { 
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABFCAYAAAD6pOBtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gMbBwwfAKopzQAAEfdJREFUeNrVW3uUHFWZ...) no-repeat;
}

You can also use data URIs within the src attribute for an HTML <img> element.

<img width="64" height="69" alt="Treehouse Logo" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABFCAYAAAD6pOBtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gMbBwwfAKopzQAAEfdJREFUeNrVW3uUHFWZ...">

Note: I’ve shortened the data URIs in these examples a bit. They tend to be very long!


Why Should I Use Them?

The main benefit to using data URIs is that you can reduce the number of HTTP requests that your site needs to make to load the page. Each individual file referenced in your CSS or HTML code will create a new HTTP request. By using data URIs, you’re actually embedding the file data directly within your HTML or CSS file, so there’s no need to make a HTTP request to fetch the resource.

Making fewer HTTP requests ultimately means your web page will load faster as the browser does not have to load as many files. Aside from actually downloading the file, it takes time for the browser to establish a connection with the server for each HTTP request that’s made. Using data URIs eliminates this overhead.

It’s worth noting that the size of the data URI string is often around a third larger than the size of the original binary file. This means that you’ll be downloading a larger amount of data overall, but it will be compressed into a single file, with a single HTTP request. That’s OK, as it’s often quicker to download a large amount of data on a single connection than it is to download the same amount of data using multiple connections (due to the request overhead we spoke about earlier).

Remember: Not everyone has the speediest internet connections. Some zoom to the front of the pack, while others lag behind. Make sure you plan for those users, too. (Photo by Flickr user Stig Nygaard)

A drawback of using data URIs is that they’re not cached by the browser. As a result, the browser will have to decode the data URIs each time the page is loaded, consuming precious system resources. Mobile browsers can be slow to decode data URIs, so you need to weigh-up the network saving against the time taken to decode the images. If you’re using a lot of data URIs in your website, make sure that you test in a variety of mobile browsers to check that this doesn’t have a negative impact on performance.

How to Create Data URIs Using Base64

So now that you understand how to use data URIs in your web pages, and why they are useful, how do you actually create them? There are a few different options available.

Use an Online Converter

There are lots of apps available online that will convert a binary file to a data URI. One that I’ve found particularly useful can be found at dataurl.net.

Use the PageSpeed Module

If you’ve been following my posts on web performance in the past, you’ll probably know by now that I’m a huge fanboy of the PageSpeed module. Once you install this module on your Apache or Nginx web server, it will take care of applying a whole bunch of performance optimisations to your site without your needing to lift a finger.

The PageSpeed module includes a feature that will automatically convert small images referenced in your HTML and CSS files to data URIs, and then embed these into your code in place of the original file paths. This means that you don’t need to manually convert your files to data URIs, you can just sit back and let PageSpeed do all the work for you.

To ensure that this feature is turned on, add the following line to your server configuration.

For Apache web servers:

ModPagespeedEnableFilters inline_images

For Nginx web servers:

pagespeed EnableFilters inline_images;

Enabling the rewrite_images filter will also turn on inline_images alongside some other optimisations.

Use Compass

If you use Compass, you have access to a few helpers that will take care of converting your files to data URIs for you.

The inline-image() helper will convert an image file to a data URI. Pass in the path to your image file as the $image parameter. The $mime-type parameter is optional.

inline-image($image, $mime-type) 

You can also embed font files as data URIs using the inline-font-files() helper.

inline-font-files([$font, $format]*)

For more information, check out the Compass documentation on inline data helpers.

Create Data URIs on the Server

Many programming languages have libraries you can use to convert a file to a base64 encoded string. All you need to do is prepend data:<mime type>;base64, to the beginning of the encoded string and you’ve got your data URI.

Check out this page for some examples of how to convert a binary file to a base64 string in commonly used programming languages.

Browser Support

Browser support for data URIs is generally very good. You just want to watch out if you need to support IE 5 to 7. If you do need to support older versions of IE, you could create an IE-specific stylesheet that switches out any styling rules with data URIs for ones that use standard file paths.

IE Firefox Chrome Safari Opera
8+ 2+ 4+ 3.1+ 9+

Support on mobile is pretty good too!

Android Browser Blackberry Chrome for Android Firefox for Android IE Mobile Safari Opera Mobile
2.1+ 7+ 33 26 10 3.1 10+

Source: http://caniuse.com/datauri

Final Thoughts on Data URIs for HTML & CSS

In this blog post, you’ve learned how to use data URIs to reduce HTTP requests and therefore increase the performance of your websites.

Web performance is something all web developers should spend some time looking into. It’s easy to forget that not everyone is afforded the same great broadband speeds you may have. A large proportion of the world’s population is just coming online, fueled by the adoption of mobile phones that rely on slow, cellular networks for access to the internet.

Next time you’re building a website, consider what you can do to ensure that you’re providing a great experience to all your users, regardless of how they’re connecting to your site.

Useful Links

Exit mobile version