Search code examples
htmlcssdata-uri

What are pros and cons of using data URIs in HTML and CSS?


Instead of linking images from external resources, it is possible to encrypt them in the HTML and CSS like this:

<img alt="" src="data:image/png;base64,R0lGODlhEAAQAM..." />

or

body {
    background: url(data:image/png;base64,R0lGODlhEAAQAM...);
}

What are the advantages and disadvantages of that compared with the usual linking? What is more preferable for high-performance websites? How supported is this feature across browsers?


Solution

  • DataURI instead of external resources in file

    Pros

    • Cached in program, is the fastest
    • Faster load times with fewer server requests
    • Works off-line everywhere and everytime
    • No man in the middle
    • Data can't be lost
    • The load event fires quicker
    • It works! Max length is 2GB

    Cons

    • Large file
    • Code is cluttered by very long strings
    • The overall data size is extended by about 33 %
    • External server can't update the data URI
    • Needs a tool or Javacript to get the DataURI
    • The DOMContentLoaded event is delayed
    • Larger download size and slower visitor experiences
    • On Mobile; 6x Slower than Source Linking

    DataURI is essentially a Base64 string. Base64 gury say:

    Pros

    1. Speeds up page loading, because the browser will not be limited by the maximum number of concurrent HTTP requests.
    2. Reduces the server load, since the browser makes only one HTTP request. As result, the server can simultaneously serve more clients.
    3. Provides a simple hotlinking protection since no one can embed images onto their pages directly from your server.
    4. Makes pages independent of external files, allowing you to easily share them even offline.
    5. Improves performance (preliminary tests showed that the browser requires less CPU).

    Cons

    1. The size of the Base64 encoded data grows by 33%.
    2. Even on minimal page changes, the browser must re-cache and reload all images.
    3. Difficult image editing, because you first need to decode the Base64 string.
    4. It is more difficult to debug, especially that Base64 strings are very long.
    5. Ignores user settings who have disabled images to save Internet bandwidth usage.
    6. It always takes up space even if images are not used on the current page.
    7. Unlike images, stylesheets block the webpage rendering.