Informatika Komputer    
   
Daftar Isi
(Sebelumnya) Data typeData warehouse (Berikutnya)

Data URI scheme

The data URI scheme is a URI scheme (Uniform Resource Identifier scheme) that provides a way to include data in-line in web pages as if they were external resources. This technique allows normally separate elements such as images and style sheets to be fetched in a single HTTP request rather than multiple HTTP requests, which can be more efficient.

Data URIs tends to be simpler than other inclusion methods, such as MIME with cid or mid URIs. Data URIs are sometimes called Uniform Resource Locators, although they do not actually locate anything remote. The data URI scheme is defined in RFC 2397 of the Internet Engineering Task Force (IETF).

In browsers that fully support Data URIs for "navigation", Javascript generated content can be provided as file "download" to the user, simply by setting window.location.href to a Data URI. One example is the conversion of HTML tables to downloadable CSV using a Data URI like this: 'data:text/csv;charset=UTF-8,' + encodeURIComponent(csv), where "csv" has been generated by Javascript.

The IETF published the data URI specification in 1998[1] as Proposed Standard on the IETF Standards Track, and hasn't progressed it since. The HTML 4.01 specification refers to the data URI scheme,[2] and data URIs have now been implemented in most browsers.

Contents

Web browser support

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

  • Gecko-based, such as Firefox, SeaMonkey, XeroBank, Camino, Fennec 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 (data URI must be base64 encoded)
      • CSS declarations that accept a URL, such as background-image, background, list-style-type, list-style and similar.
    • Internet Explorer 9: Internet Explorer 9 does not have 32KB limitation and allowed in broader elements.

Email Client support

Following clients support data uri for images[3]

  • Apple Mail 4
  • BlackBerry Curve
  • HTC HD7
  • iPad 2
  • iPhone 3GS
  • LG Optimus
  • Lotus Notes 8
  • Me.com
  • Nokia N96
  • Outlook 2003
  • Thunderbird 3
  • Yahoo! Mail

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 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

  • Data URIs are not separately cached from their containing documents (e.g. CSS or HTML files) so data are 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 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 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 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)[8]
  • Data URIs do not carry a filename as a normal linked file would. When saving, a default filename 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]

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.

Examples

HTML

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

<img src="data:image/png;base64,iVBORw0KGgoAAA ANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w 38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" 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,iVBORw0KGgoAAA ANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlB MVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h /1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9z wz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTk SuQmCC') no-repeat scroll left top;}

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

Because user agents must ignore a declaration with an unknown property,[10] a fallback to a regular url is possible using standard CSS:

div.menu { background-image: url('elephant.png'); background-image: url('data:image/png;base64,iVBORw0KGgoAAA ANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAABlB MVEUAAAD///+l2Z/dAAAAM0lEQVR4nGP4/5/h /1+G/58ZDrAz3D/McH8yw83NDDeNGe4Ug9C9z wz3gVLMDA/A6P9/AFGGFyjOXZtQAAAAAElFTk SuQmCC');}

JavaScript

A 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>& lt;/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]

Inclusion in HTML or CSS using PHP

Because base64-encoded data URIs are not human readable, a website author might prefer the encoded data be included in the page via a scripting language such as PHP. This has the advantage that if the included file changes, no modifications need to be made to the HTML file, and also of keeping a separation between binary data and text based formats. Disadvantages include greater server CPU use unless a server-side cache is used.

<?phpfunction data_uri($file, $mime) { $contents = file_get_contents($file); $base64 = base64_encode($contents); return "data:$mime;base64,$base64";}?> <img src="<?php echo data_uri('elephant.png', 'image/png');?>" alt="An elephant">

Similarly, if CSS is processed by PHP, the below function may also be used:

<?php header('Content-type: text/css'); ?> div.menu { background-image:url('<?php echo data_uri('elephant.png', 'image/png'); ?>');}

Python

data_uri = open("sample.png", "rb").read().encode("base64").replace("\n", "")img_tag = '<img alt="sample" src="data:image/png;base64,{0}">'.format(data_uri)print img_tag

Python 3

import base64data_uri = str(base64.encodestring(open("sample.png", "rb").read()) , "utf8").replace("\n", "")img_tag = '<img alt="sample" src="data:image/png;base64,{0}">'.format(data_uri)print(img_tag)

Ruby 1.9.3

require "base64"data_uri = Base64.encode64(File.open("sample.png", "rb").read).gsub(/\n/, "")image_tag = '<img alt="sample" src="data:image/png;base64,%s">' % data_uriputs image_tag

Perl

use MIME::Base64 qw(encode_base64); open FH, '<', 'sample.png';read(FH, $contents, 10000000);$base64_data = encode_base64($contents, ""); print '<img alt="sample" src="data:image/png;base64,' . $base64_data . '">';

JavaScript (node.js)

var fs = require('fs');var base64_data = new Buffer(fs.readFileSync('sample.png')).toString('base64');console.log('<img alt="sample" src="data:image/png;base64,' + base64_data + '">');

See also

  • MHTML, an alternative for attaching resources to an HTML document usually found in HTML email messages
  • MIME for the used mediatypes

References

  1. ^ Masinter, L (August 1998). "RFC 2397 - The "data" URL scheme". Internet Engineering Task Force. http://tools.ietf.org/html/rfc2397. Retrieved 2008-08-12.
  2. ^ Raggett, Dave; Le Hors, Arnaud; Jacobs, Ian (1999-12-24). "Objects, Images, and Applets: Rules for rendering objects". HTML 4.01 Specification. World Wide Web Consortium. http://www.w3.org/TR/1999/REC-html401 -19991224/struct/objects.html#h-13.3. 1. Retrieved 2008-03-20.
  3. ^ a b c "IE9 Beta Minor Changes List". Eric Law. http://blogs.msdn.com/b/ieinternals/a rchive/2010/09/15/ie9-beta-minor-chan ge-list.aspx. Retrieved 2010-10-28.
  4. ^ a b c "data Protocol". Microsoft Developer Network. Microsoft. http://msdn.microsoft.com/en-us/libra ry/cc848897%28VS.85%29.aspx. Retrieved 2009-01-05.
  5. ^ "RFC 2616 Section 8.1.4". Internet Engineering Task Force.
  6. ^ "CSS Inline Images and the Data URI". http://www.7cynics.com/webdesign/css/ css-inline-images-data-uri.html.
  7. ^ "Data URI support in Microsoft browsers". http://www.google.com/search?q=ie%20d ata%20uri%20supported%20site:microsof t.com&btnI=1. Retrieved 2012-04-09.
  8. ^ Martin Isenburg, Jack Snoeyink (2003). "Binary Compression Rates for ASCII Formats". http://citeseerx.ist.psu.edu/viewdoc/ summary?doi=10.1.1.13.7233. Retrieved 2011-04-07.
  9. ^ Masinter, L (August 1998). "Security". RFC 2397 - The "data" URL scheme. Internet Engineering Task Force. pp. 2. http://tools.ietf.org/html/rfc2397. Retrieved 2008-08-12.
  10. ^ "W3C CSS2.1 specification: Rules for handling parsing errors". World Wide Web Consortium. 7 June 2011. http://www.w3.org/TR/CSS2/syndata.htm l#parsing-errors. Retrieved 2010-09-08.

External links

(Sebelumnya) Data typeData warehouse (Berikutnya)