Use tag with data:url as embedded image

2018-01-03 20:04:00 UTC

<img> tag can treat base64 encoded text for `src` attribute.

According Embedding an image via data: URL section in Using images - Web APIs | MDN

That's like this:

Pros. is very clear. It reduces a request to fetch that image (DNS lookup, request and downloading etc.). And it might be portable code.

One advantage of data URLs is that the resulting image is available immediately without another round trip to the server. Another potential advantage is that it is also possible to encapsulate in one file all of your CSS, JavaScript, HTML, and images, making it more portable to other locations.

The problem using this way is, that image is not cached, and it's hard for large size image. (usage and for also coding)


If you have a png file which you want use with this way, how to get encoded text with base64? That's very easy. For example, in Python.

And just append it to data:image/png;base64, in src attribute of <img> tag.

About its specification and syntax of data: URL, You should see RFC 2397 and Data URLs - HTTP | MDN

Syntax is:

According to RFC2397, It seems that some applications (browsers?) have length limit for this data URLs.

The "data:" URL scheme is only useful for short values. Note that some applications that use URLs may impose a length limit; for example, URLs embedded within <A> anchors in HTML have a length limit determined by the SGML declaration for HTML [RFC1866]. The LITLEN (1024) limits the number of characters which can appear in a single attribute value literal, the ATTSPLEN (2100) limits the sum of all lengths of all attribute value specifications which appear in a tag, and the TAGLEN (2100) limits the overall length of a tag.

| However, Firefox and most other modern browsers moment don't have length limit for this. | Anyway, it's apparently bad idea for long (large) size image.


| There is a small jpeg image of my profile icon :) | Its size is 1.3KB, width is 25px and height is 25px.

This is a image using data:url

| I think, the caching issue might be also an advantage for images which we don't want to be cached on browser. | Recently I used this way for a browser widget's icon to reduce a request to server.

This way might be also good, when you create image programatically.