data: URIs are a very useful way to embed small items of data into a URL—rather than link to an external resource, the URL contains the actual encoded data.
data: URIs are supported by most modern browsers except for some versions of Internet Explorer. IE is still the dominant browser in use today and this lack of support does mean that
data: URIs still aren't really suitable for general use on the web. If you know that you are using a browser that does support them, however—Firefox, Opera or Safari, for example—then you can do some interesting things with them. If you're using an unsupported browser to view this page, then I'm afraid you won't be able to see the examples.
One of the most commonly seen uses today of the
data: URI scheme is in Greasemonkey scripts. If you need to include graphics, or indeed other data elements in your Greasemonkey script, you can avoid having to store them on a central server by embedding them into your script directly via the use of
For example, if you wanted to include a logo in the output of your Greasemonkey script, you would generate an
<img> tag. Normally, the
src attribute of this tag would have to refer to a image hosted on the Internet somewhere—something like this:
<img src="http://www.yourserver.com/logo.gif" />This means that every installation of this script would access your server every time it needed the image. Just as importantly, if your server was ever unavailable for any reason, your script would then fail to function correctly. To get around this, simply encode the logo as a
<img src="data:image/gif;base64,R0lGODlhyAAiALM...DfD0QAADs=" />Which then looks like this:
Note: I haven't displayed the full URL in the example above as it's rather long. View the source of this page if you want to see it in all its glory.
The logo shown above is a little over 1K in size. You should remember that base64 encoding (which is commonly used in
data: URIs will add around 30% to the size of your data.
You can even encode larger objects as
data: URIs too:
You should be careful with the size of your
data: URIs, as browsers will quite likely have internal limits as to the length of URIs that they can comfortably cope with. The photo above is around 45K, and displays quite happily in Firefox. Other browsers, such as Opera, may well impose lower limits on URI length. If in doubt, check how things look in the various browsers that you expect to be used.
Objects embedded within
data: URIs don't have to be images either. Below (if your browser supports data: URIs), you can see an example of an <iframe> tag used with a
data: URI containing an HTML page.
This is just a very brief introduction to the world of
data: URIs—if you want to learn more about them in all their gory detail, then the IETF document RFC 2397 is where you will find their full definition.
Back to the
data: URI Generator