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 14-day 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 Data URIs?

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).

Speeding cyclists by Stig Nygaard via Flickr.

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 Do I Create Data URIs?

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.

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.

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.

Creating 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 for Data URIs

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

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

Free Workshops

Watch one of our expert, full-length teaching videos. Choose from either HTML, CSS or Wordpress.

Start learning

Comments

14 comments on “Using Data URIs to Speed Up Your Website

    • Hi Ian,

      Thanks for the link. I hadn’t seen this article.
      I mainly use data URIs for small images (read: icons) and feel this is okay because the decoding time is fairly minimal.
      As mentioned in the article you referenced, it’s easy to shift the performance bottleneck from the network, to decoding data URIs if you’re not careful.

      I’ve added an extra paragraph to the post that addresses some of these issues.

  1. Using Data URIs might be good in cases where the network speed is your biggest bottleneck for performance. For example a page with lots of tiny files that don’t change often might benefit from having Data URIs instead of linked resources. But by using DATA URIs you’re increasing cpu/memory usage to decode them every time the page loads instead of just caching them after the first page load.

    • Hi Christopher,

      Thanks for pointing out the caching and decoding issues.
      I’ve amended the post with some extra information to ensure that these drawbacks are clear.

      :)

  2. Few points
    —————-
    * Browser cache will not work for Data URIs. Which is really huge we don’t want to load an image from the server each time we loads the page. So use it carefully
    * In mobile browser having lots of replacements will affect the CPU performance

  3. Thanks for another informative website. The place else could I am getting that type of information written in such an ideal approach? I have a project that I am just now operating on, and I have been at the look out for such information.

  4. I will recommend not to use data URIs for mobile optimized websites, or if we want to use then use only at certain places not every where. Access use of URI will slower down the mobile performance and would also cause more bit consumption on cellular networks data plans. So, if we are using them we should use them with great care and precision. Though data URIs are very useful, i have heard about them but never use before, after reading your blog post, i got a more clear picture of URIs. Thanks for such an informative sharing.

  5. Nice thoughts (PageSpeed etc). But what about meta tags? Using shared hosting on a biz-class server, seems fast enough for a string of big graphics. Less file-size with sound file, host does not like, so file type is another ‘technical’ factor, yes?. http://www.riverleaf.net