Using an Image File Vs Data Uri in The CSS

Using an image file vs data URI in the CSS

I don't think you will gain much... and if it is a file image, the browser can cache it. I wouldn't bother doing it with CSS unless you have a real need for it.

What are drawbacks of using data URI instead of sprite images?

If any image changes, the entire css file has to change. This breaks HTTP cache. With a sprite image, the css file itself would be served from cache, and only the changed image would have to be downloaded again.

It may be better to generate a css file only for the data:URI images, and another for the regular CSS stuff. This way, regular css updates don't require re-downloading the data:uri images.

Second problem is with foreground images, those that are served with <img> tag in the html. If it is a frequently used image, it will unnecessarily increase the size of the html.

Clarification regarding validity of using data-URIs in CSS url()

data: URIs are actually valid URLs as per RFC 2397, don't worry, they are still allowed.

Not sure what this MDN article tried to imply when it says "such as a data-uri", but I did edit it out to URN since it's actually what happened in CSS 2:

The specs did indeed extend the <url> notation to all URIs, by allowing Uniform Resource Names to be part of it too... I can't tell why they did this change, but it seems very weird to say the least, as I can't see how an URN could be any useful in a stylesheet... According to the specs wording, it seems its authors didn't quite know yet what it would be.

URLs (Uniform Resource Locators, see [RFC1738] and [RFC1808]) provide the address of a resource on the Web. An expected new way of identifying resources is called URN (Uniform Resource Name). Together they are called URIs (Uniform Resource Identifiers, see [URI]). This specification uses the term URI.


Ps: Specs define it as "data: URLs" from the fetch API.

What is the purpose of data URIs?

1. Reducing server requests

Data URIs can be used to decrease server load and improve client performance, by reducing the number of HTTP requests required to acquire resources. For example, this HTML:

<img src="assets/bullet.png">

... can be replaced with this:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAALCAYAAACprHcmAA
ABFklEQVQY022RoW4CURBFD2ETymYFigRDEEgcFoNBIcAj0AQLH0AVfAEOQ0IgCP6C7L5ZWlpBG5
o2paJJ01JR/6aCbrI03GTcmZk7c+GfAkj54PqQDsDhkgSuDNQ3njff5vO7bS4XCgx9KJ2B5gReG9
D30UiPy6UeFwt96/X0Nps9+FCNw3UDakCfWy37WKvpU7Npv1cr+zEe600msw/AQyAlMJcTbKMmA3
pfLOrPeq0PlYoaaGDAFdgJaLwMaAD6OZnoodvV0HEGCKQFwj/IxmED+jWb2Zd2WyWZ7CPgGBhegj
eua187Hb0rFNRAOTqwJHAw51ZsZMXAVBIJJ/7nqsA+mhrbMBXIXQrGE2gYGAj0BcoSS/EXVfKm38
k6jyMAAAAASUVORK5CYII="
>

... to produce an image like this: bullet icon with one fewer HTTP request.

Note: it appears to be impossible to embed data URI images in a Stack Overflow post; however, the image above was uploaded to an image hosting service using the data URI shown.

If, for example, your site uses many small icons, specifying them all as data URIs in a stylesheet:

.icon-bullet-red { background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAALCAYAAACprHcmAAABFklEQVQY022RoW4CURBFD2ETymYFigRDEEgcFoNBIcAj0AQLH0AVfAEOQ0IgCP6C7L5ZWlpBG5o2paJJ01JR/6aCbrI03GTcmZk7c+GfAkj54PqQDsDhkgSuDNQ3njff5vO7bS4XCgx9KJ2B5gReG9D30UiPy6UeFwt96/X0Nps9+FCNw3UDakCfWy37WKvpU7Npv1cr+zEe600msw/AQyAlMJcTbKMmA3pfLOrPeq0PlYoaaGDAFdgJaLwMaAD6OZnoodvV0HEGCKQFwj/IxmED+jWb2Zd2WyWZ7CPgGBhegjeua187Hb0rFNRAOTqwJHAw51ZsZMXAVBIJJ/7nqsA+mhrbMBXIXQrGE2gYGAj0BcoSS/EXVfKm38k6jyMAAAAASUVORK5CYII=) }
.icon-bullet-green { background-image: /* ... */ }
.icon-save { background-image: /* ... */ }
.icon-load { background-image: /* ... */ }
.icon-delete { background-image: /* ... */ }
/* ... etc. */

... can eliminate a large number of HTTP requests, at the cost of overall download size, legibility, and an increased likelihood that a bad edit might render the URI nonsensical (and difficult to fix).

An alternative method to achieve the same result for images is the use of CSS sprites.

2. Embedding content in a single file

A data URI can be used to contain all of the resources required to correctly display a page in a single document. This may be useful in e.g. a README file distributed alongside a piece of software. In theory, data URIs could also be used as an alternative to the use of attachments to embed resources in HTML email, but in practice client support for data URIs is too unreliable for this to be a useful technique.

3. Avoiding browser warnings

Some browsers display a warning if a page contains content served over a mixture of HTTP and HTTPS. If your server is set up so that static content like images is typically served over HTTP, but dynamic content is served over HTTPS, embedding that static content with a data URI is a possible workaround.

Why use data URI scheme?

According to Wikipedia:

Advantages:

  • HTTP request and header traffic is not required for embedded data, so
    data URIs consume less bandwidth whenever the overhead of encoding
    the inline content as a data URI is smaller than the HTTP overhead.
    For example, the required base64 encoding for an image 600 bytes long
    would be 800 bytes, so if an HTTP request required more than 200
    bytes of overhead, the data URI would be more efficient.

  • For transferring many small files (less than a few kilobytes each), this can be faster. TCP transfers tend to start slowly. If each file requires a new TCP connection, the transfer speed is limited by the round-trip time rather than the available bandwidth. Using HTTP keep-alive improves the situation, but may not entirely alleviate the bottleneck.

  • When browsing a secure HTTPS web site, web browsers commonly require that all elements of a web page be downloaded over secure connections, or the user will be notified of reduced security due to a mixture of secure and insecure elements. On badly configured servers, HTTPS requests have significant overhead over common HTTP requests, so embedding data in data URIs may improve speed in this case.

  • Web browsers are usually configured to make only a certain number
    (often two) of concurrent HTTP connections to a domain, so inline
    data frees up a download connection for other content.

  • Environments with limited or restricted access to external resources
    may embed content when it is disallowed or impractical to reference
    it externally. For example, an advanced HTML editing field could
    accept a pasted or inserted image and convert it to a data URI to
    hide the complexity of external resources from the user.
    Alternatively, a browser can convert (encode) image based data from
    the clipboard to a data URI and paste it in a HTML editing field.
    Mozilla Firefox 4 supports this functionality.

  • It is possible to manage a multimedia page as a single file. Email
    message templates can contain images (for backgrounds or signatures)
    without the image appearing to be an "attachment".

Disadvantages:

  • Data URIs are not separately cached from their containing documents
    (e.g. CSS or HTML files) so data is downloaded every time the
    containing documents are redownloaded. Content must be re-encoded and
    re-embedded every time a change is made.

  • Internet Explorer through version 7 (approximately 15% of the market as of January 2011), lacks support. However this can be overcome by serving browser specific content.
    Internet Explorer 8 limits data URIs to a maximum length of 32 KB.

  • Data is included as a simple stream, and many processing environments (such as web browsers) may not support using containers (such as multipart/alternative or message/rfc822) to provide greater complexity such as metadata, data compression, or content negotiation.

  • Base64-encoded data URIs are 1/3 larger in size than their binary
    equivalent. (However, this overhead is reduced to 2-3% if the HTTP
    server compresses the response using gzip) Data URIs make it more
    difficult for security software to filter content.

According to other sources
- Data URLs are significantly slower on mobile browsers.

CSS sprites vs data URIs

Base64-encoded data is about 1/3 larger than raw bytes, so on pages where downloading all the image data takes more than three times as long as making a request, CSS sprites are superior from a performance basis.

Also, inline data URIs make the file itself take as long to load as the actual data plus the base64-encoded images. If the data URIs are on your actual HTML page, that means rendering stops and waits for the image to load. If the data URIs are in your stylesheet, that means any rules after the data URI have to wait for it before they can be processed. On the other hand, with a sprite file, the images can load concurrently with your other resources. That may be worth the cost of one extra request, especially when you factor in the base64 penalty.



Related Topics



Leave a reply



Submit