Course notes 9
syllabus | schedule | exercises | assignments | class notes | resources | students | ARTC courses

Data URIs

When trying to minimize the load time of a website there are several important statistics that need to be considered. The first, and most easily understood, is the actual size of files that a user must download to view a website. In addition, the number of files is also important. Every time a resource is requested, the browser must connect to the server and retrieve it. This is called an HTTP request, and in many cases is the most important factor in improving website performance. Each individual request takes time, and most browsers will only allow two concurrent connections to the server at a time. Minimizing the number of requests that have to be made will allow for the site to download faster.

Traditional methods for minimizing http requests involve combining and minimizing javascript or css files, adding css or scripts directly onto the page, utilizing css sprites instead of javascript for rollovers and creating image maps. Another method is using data URIs for images. Data URIs are a method in which we can take an image or resource, encode it into a string, and embed that into a html/css file, instead of linking to the external image or resource. In addition to eliminating a html request, this also means that it will now be cached as part of the html or css file.

The above image in included in a <img> tag with a data uri. The code is as follows:

   <img width="150" height="150" title="" alt="" 
       src="data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAA..." />

Data URIs can be used the same way in css files, with images substituting the url() for data: . URIs can be generated in a server side language, or there are several online tools to create them.

Using Data URIs can be a great effect to influence the performance of a page, but there is a downside. Embedding an image as a URI is more expensive in terms of file size than the actual image. Using them is a trade off between total size and number of http requests.

Data URIs are most useful in situations where an image is small, yet important, appears often, and does not change. This kind of scenario would take full advantage of the caching ability of the technique, possibily offsetting the small increase in file size. Google implements this technique to great effect with the logo on the mobile version of its Gmail web application.