What else can we do with data-uri?

This article was first published on CSS-101 (04-01-2011).

I started thinking of data-uri as a mean to reduce HTTP requests and file size. Then I thought it could be used as a hack to delay the execution of “downloaded” scripts.

data-uri inside URI

URIs containing data-uri can reduce HTTP requests and file size. This technique could also be used to lazy load assets from pages that already perform well.

These are the results of YSlow for 3 different “import” methods:

Image path in Source

Demo

Empty Cache Primed Cache
HTTP Requests - 11 1 HTML/Text 1.8KB
Total Weight - 29.1KB
1 HTML/Text 1.8KB
5 CSS Image 6.6KB

data-uri in Source

Demo

Empty Cache Primed Cache
HTTP Requests - 10 1 HTML/Text 6.5KB
Total Weight - 29.4KB
1 HTML/Text 6.5KB
4 CSS Image 2.2KB

data-uri in URI

Demo

Empty Cache Primed Cache
HTTP Requests - 10 1 HTML/Text 1.8KB
Total Weight - 24.7KB
1 HTML/Text 1.8KB
4 CSS Image 2.2KB

(Note: there is more to it when it comes to performance. With very long URIs, packetization comes into play which increases TCP transport time.)

Executing scripts on demand

With data-uri, we can create a script node dynamically without downloading a file. Like this:

<script>
f = function(){
    var plug=document.createElement('script');
    plug.setAttribute("src", "data:application/x-javascript;base64,YWxlcnQoIkhlbGxvIFdvcmxkISIp");
    document.getElementsByTagName("head")[0].appendChild(plug);
}
</script>

Things to consider

These demos are just proof-of-concept. Security and browser compatibility are obvious issues, and relying on JavaScript to extract images from URIs should also be a concern.

URL’s length is also a factor to consider. I believe href values cannot exceed 1024 characters and server could return 414 Errors (URI Too Large) if requested URLs’ length exceed the capacity limit for the server (even though the spec for the HTTP protocol does not specifiy any limit).

Share