Reducing Web Requests Using DATA URI Scheme (Alternative to CDN?)

PerformanceHTML5JavaScriptCloudDrupal

How to use the DATA URI scheme to embed images directly in your HTML/CSS and reduce HTTP requests

Reducing Web Requests Using DATA URI Scheme (Alternative to CDN?)

To decrease the loading time for web pages, we adopt different methods. One of the most effective is reducing the number of HTTP requests. This is why many developers use CSS Sprites for situations where you have multiple small images used as backgrounds for HTML elements.

But CSS Sprites only work when using images as backgrounds. What about images that need to be displayed with image tags? Traditionally, we'd look to Content Delivery Networks (CDNs) for optimization. However, there's another approach worth considering: DATA URI scheme.

What is DATA URI?

The DATA URI scheme allows you to embed small files directly into your HTML or CSS as a base64 encoded string. Instead of linking to an external resource, you include the actual content inline.

<!-- Traditional image tag -->
<img src="small-icon.png" alt="Icon">

<!-- Same image using DATA URI -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAJhSURBVDjLY/j//z8DJZiBKgb8f9ElESs9BYuZF7Hpf3gHN1FGQDR++v9dINPdO6vTz9k+yg+u8f+v/9f+n/998/8PvukF4jtM6Ib8f+APtcX/Dv+JQHwfpPH6/1v/z/+/9P/Gj0f/p31f+n8PWIySIX9fNIZ2b2D8bnpo37+n84HiW4H4IRDfBWL37up0oD5ULxgDFfx9NiYt9c3rDUn+QXdmF2XPPr88zgGo+N+wR0v/uU1yBwpuhWr4/q5FUh4Wc36+6FZ68eCBn29u3Pz/5vmLX+/tXX5xW5e4gzlQw5Olsz+5z0xMhBrw/1/34DRDSzjN8OfVdOWIjbvb/t+79///5y/+Z58t+V8TYqTIBNRQsLXx/76N1cUQDf9fdsrEGrqK2f38TE/Zi0tz/j9+8OP/zn23/idNyPnfGuhkBdSQf7Lt/9oDNQ0QDf9edwkVz4w1XPHr0x6N8nvPtz98hGEASNPkfWX/l+wq3APR8O9Zi+DTc5OSF78/PEXj/tfPHSCv/f//+cv/9YuucGgCaZi+teJ//85kQ4iGP28ma57c33Lr25v1xvr3nt5c/ev3/69f//9//OL/mfMvGa+eP8DAANJQsb35/659JZkQDd+ftfD9fb3WwuTjh1lmE46+WVd97/+7D///v3z7/8GDF/837Tn63/9A68ddO8oFIRrO7KqRuXtr9b8fTyeoev9/vc3a79rax3cvXtD9ef/6Qj3vA037C+ds/v/1xdP/R07e+X9g74H/T+5e+n9oQ+v/jRuWxIPcS3EsUJKUKQYAQVQcGGF4uUcAAAAASUVORK5CYII=" alt="Icon">

Advantages of DATA URI

  1. Reduced HTTP requests: Each HTTP request has overhead in terms of DNS lookup, TCP connection establishment, and HTTP headers. DATA URIs eliminate these requests.

  2. Immediate availability: The browser doesn't need to make a separate request to fetch the resource - it's already there in the HTML/CSS.

  3. Caching benefits: When you include DATA URIs in your CSS files, they get cached along with the CSS.

  4. Parallel download limit bypass: Browsers limit the number of concurrent connections to a domain, but DATA URIs don't count toward this limit.

Implementation in Practice

Here's how to convert an image to a DATA URI:

// Using JavaScript to convert an image to DATA URI
function getDataURI(img) {
  // Create canvas element
  var canvas = document.createElement('canvas');
  canvas.width = img.width;
  canvas.height = img.height;
  
  // Draw image on canvas
  var ctx = canvas.getContext('2d');
  ctx.drawImage(img, 0, 0);
  
  // Get DATA URI
  return canvas.toDataURL('image/png'); // Or 'image/jpeg' for JPG images
}

// Usage
var img = new Image();
img.onload = function() {
  var dataURI = getDataURI(this);
  console.log(dataURI); // Use this URI in your HTML/CSS
};
img.src = 'small-icon.png';

For server-side conversion, many languages have libraries to handle this. For example, in PHP:

// PHP function to convert image to DATA URI
function imageToDataURI($imagePath) {
  $mime = mime_content_type($imagePath);
  $data = base64_encode(file_get_contents($imagePath));
  return 'data:' . $mime . ';base64,' . $data;
}

Considerations and Limitations

While DATA URIs offer advantages, they have limitations:

  1. Base64 overhead: Base64 encoding increases the file size by approximately 33%.

  2. Browser support: While modern browsers support DATA URIs well, IE7 and below have significant limitations.

  3. Caching granularity: Individual images can't be cached separately - they're part of the containing document.

  4. Parsing overhead: Browsers may take longer to parse large DATA URIs.

  5. File size: DATA URIs are most effective for small images (typically under 5KB).

Best Practices

  • Use DATA URIs for small, frequently used images
  • Implement them in your CSS rather than inline HTML where possible
  • Consider using sprites for larger collections of images
  • Test performance in your specific use case

Comparison with CDNs

DATA URIs are not a replacement for CDNs but can complement them:

| Feature | DATA URI | CDN | |---------|----------|-----| | Reduces HTTP requests | Yes | No | | Geographic distribution | No | Yes | | Effective for large files | No | Yes | | Requires external service | No | Yes | | Browser caching benefits | Limited | Full |

Conclusion

DATA URIs offer a viable technique for reducing HTTP requests and improving initial page load times, especially for smaller images. While they won't replace CDNs in all scenarios, they provide another tool in your web performance optimization toolkit.

For modern web applications with many small icons and decorative elements, a hybrid approach of CSS sprites, DATA URIs, and CDN-delivered resources often provides the best overall performance.

Note: This article was migrated from the original A thousand nodes blog (2011)

Continue Reading

Browse All Articles