Data URI scheme

[Fuente:             http://en.wikipedia.org/wiki/Data_URI_scheme]

El esquema data URI es un URI scheme (Uniform Resource Identifier scheme) que proporciona una forma de incluir datos in-line en páginas web como si fueran recursos externos. Esta técnica te permite por ejemplo descargar en una sola petición HTTP imágenes y hojas de estilos antes que hacer múltiples peticiones HTTP lo cual puede ser ineficiente.

Los data URIs tienden a ser más simples que métodos de inclusión, tales como MIME with cid or mid URIs. Los data URIs se les llama algunas veces URL (Uniform Resource Locators) , aunque no referencien nada remoto. El esquema data URI está definido en RFC 2397 of the Internet Engineering Task Force (IETF).

En los browsers que soportan completamente Data URIs para “navigation”, contenido generado por Javascript se le puede provocar como si fuera una descarga de fichero para el usuario, simplemente asignando el Data Uri al window.location.href. Como ejemplo valga la conversión de tablas HTML a CSV para descargar utilizando Data un URI como este:

data:text/csv;charset=UTF-8,' + encodeURIComponent(csv)

donde “csv” ha sido generado por Javascript.

La IETF publicó la especificación data URI en 1998 y no ha cambiado desde entonces. La especificación HTML 4.01 se refiere al data URI scheme y este esquema ha sido implementado en la mayoría de los navegadores.

Web browser support

As of March 2012, Data URIs are supported by the following web browsers:

  • Gecko-based, such as FirefoxSeaMonkeyXeroBankCaminoFennec and K-Meleon
  • Konqueror, via KDE‘s KIO slaves input/output system
  • Opera (including devices such as the Nintendo DSi or Wii)
  • WebKit-based, such as Safari (including iOS), Android‘s browser, Kindle 4’s browser, Epiphany and Midori (WebKit is a derivative of Konqueror’s KHTML engine, but Mac OS X does not share the KIO architecture so the implementations are different), and Webkit/Chromium-based, such as Chrome
  • Trident
    • Internet Explorer 8: Microsoft has limited its support to certain “non-navigable” content for security reasons, including concerns that JavaScript embedded in a data URI may not be interpretable by script filters such as those used by web-based email clients. Data URIs must be smaller than 32 KB in Version 8.[3] Data URIs are supported only for the following elements and/or attributes:[4]
      • object (images only)
      • img
      • input type=image
      • link
      • CSS declarations that accept a URL, such as background-imagebackgroundlist-style-typelist-style and similar.
    • Internet Explorer 9: Internet Explorer 9 does not have 32KB limitation and supports more elements.

Email Client support

Following clients support data URI for images[3]

Format

data:[<MIME-type>][;charset=<encoding>][;base64],<data>

The encoding is indicated by ;base64. If it’s present the data is encoded as base64. Without it the data (as a sequence of octets) is represented using ASCII encoding for octets inside the range of safe URL characters and using the standard %xx hex encoding of URLs for octets outside that range. If <MIME-type> is omitted, it defaults to text/plain;charset=US-ASCII. (As a shorthand, the type can be omitted but the charset parameter supplied.)

Some browsers (Chrome, Opera, Safari, Firefox) accept a non-standard ordering if both ;base64 and ;charset are supplied, while Internet Explorer requires that the charset’s specification must precede the base64 token.

Advantages and disadvantages

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 fasterTCP 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.
  • While web browsers will not cache inline-loaded data as separate resource, external CSS files using data URIs are cached, so that an external CSS file with 10 background-images embedded as data URIs requires only one initial request instead of eleven and subsequent requests require only retrieving one cached CSS file, instead of one CSS file plus ten cached images.
  • 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 of (often two) concurrent HTTP connections to a domain,[5] 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[edit]

  • Data URIs are not separately cached from their containing documents (e.g. CSS or HTML files), therefore the encoded data is downloaded every time the containing documents are re-downloaded.
  • Content must be re-encoded and re-embedded every time a change is made.
  • Internet Explorer through version 7 (approximately 5% of web traffic as of September 2011), lacks support. However this can be overcome by serving browser-specific content.[6]
  • Internet Explorer 8 limits data URIs to a maximum length of 32 KB. (Internet Explorer 9 does not have this limitation)[3][4]
  • In IE 8 and 9, data URIs can only be used for images, but not for navigation or JavaScript generated file downloads.[7]
  • Data URIs are 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 metadatadata compression, or content negotiation.
  • Base64-encoded data URIs are 1/3 times larger in size than their binary equivalent. (However, this overhead is reduced to 2–3% if the HTTP server compresses the response using gzip)[8]
  • Data URIs do not carry a file name as a normal linked file would. When saving, a default file name for the specified MIME type is generally used.
  • Referencing the same resource (such as an embedded small image) more than once from the same document results in multiple copies of the embedded resource. In comparison, an external resource can be referenced arbitrarily many times, yet downloaded and decoded only once.
  • Data URIs make it more difficult for security software to filter content.[9]

Examples

HTML

An HTML fragment embedding a picture of small red dot: Red-dot-5px.png

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />

As demonstrated above, data URIs encoded with base64 may contain whitespace for readability.

CSS

A CSS rule that includes a background image:

ul.checklist li.complete {
    padding-left: 20px;
    background: white url('data:image/png;base64,iVBORw0KGgoAA
AANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlBMVEUAAAD///+l2Z/dAAAAM0l
EQVR4nGP4/5/h/1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9zwz3gVLMDA/A6
P9/AFGGFyjOXZtQAAAAAElFTkSuQmCC') no-repeat scroll left top;
}

In Mozilla Firefox 5Google Chrome 17, and IE 9 (released June, 2011), encoded data must not contain newlines.

JavaScript

JavaScript statement that opens an embedded subwindow, as for a footnote link:

window.open('data:text/html;charset=utf-8,' + 
    encodeURIComponent( // Escape for URL formatting
        '<!DOCTYPE html>'+
        '<html lang="en">'+
        '<head><title>Embedded Window</title></head>'+
        '<body><h1>42</h1></body>'+
        '</html>'
    )
);

This example does not work with Internet Explorer 8 due to its security restrictions that prevent navigable file types from being used.[4]