Embedding images directly in your HTML for fun and profit
For the uninitiated, a URI (also called, informally, a URL) is a string of characters used to identify any kind of information resource. Most often, you’ll see these things when browsing the web.
The URI scheme is basically the first part of the URI. URIs that point to web pages start with “http:”. Those that point to local stuff on your computer start with “file:”. If they refer to an email address, they start with “mailto:”, and telephone numbers start with “tel:”.
Almost all URIs point to a location (web server, file, etc.) where the desired information can be found. But there is one special case: the “data” URI scheme. If a URI starts with “data:”, it says “you don’t have to look for your information elsewhere, it is included right here in the URI itself. All you have is to specify the media type of the data (Is it an image? A piece of text? Or something weird and fancy?); and then, the encoding convention used (usually Base64).
So it goes:
So, like the title says, an obvious way to use it is to include images directly within your HTML code instead of storing them in a separate file. Here is an example of an HTML fragment embedding a picture of small red dot:
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">
Before we get all excited, a good question would be: when should we actually do something like this? Obviously, using “data” URIs has several disadvantages. First, when reusing the same resource in different places, it’s more difficult to make changes. Content must be re-encoded and re-embedded every time a change is made. Also, data URIs are not separately cached from their containing documents, so all the data has to be downloaded over and over again, every time the containing document is reloaded. And finally, some older browsers don’t provide good support for a data URI.
One possible use case is when transferring small images over a network with a large latency. That’s the case with mobile internet (EDGE or 3G). The waiting time and overhead to initiate a new connection is substantial, so if we’re talking about a really small amount of data, it’s just not worth it to transfer that data separately. Instead, we can bundle it together with the main document. That would provide some advantage to a site optimized for mobile phones.