Using Base64 in Data URIs
Learn when to use Base64 in Data URIs
What are Data URIs?
Data URIs are uniform resource identifiers with the data contained in the URI itself. URIs are similar to URLs, but URLs are a subset of URIs.
Data URIs always begin with the data:
scheme, followed by the content encoding (e.g. text/html
, text/plain
, etc.), followed by the content itself. The content can be provided in any browser-supported character set scheme, such as US-ASCII, UTF-8 and Base64. If the content is encoded with an encoding scheme other than US-ASCII, the encoding scheme must be defined before the content itself. (e.g. ...;base64,content...
)
Origin of Data URIs
The Data URI scheme is defined by RFC 2397 published in 1998. A properly-formed Data URI looks like: data:[<mediatype>][;base64],<data>
. The only required parts are data:,<data>
, all other parts are optional. Note the comma before the data, which is required.
Uses and supported content
Any mime type is supported for Base64 data, including images and plain text. Encoding images is the most common use of Base64 in data URIs, due to its performance benefits. Base64-encoded images are embedded in HTML and CSS to save the overhead of additional network requests. This technique helps improve page performance, especially in websites with lots of smaller images or icons which would otherwise result in a large number of requests.
Examples
Data URIs often contain Base64-encoded data. For example, this URI shows Hello World in HTML: data:text/html;base64,PGgxPkhlbGxvIFdvcmxkPC9oMT4=
To see it in action, manually copy and paste the data URI above into a new tab's address bar. Data URIs generally cannot be opened via links or JavaScript due to browser security restrictions.
Other examples include:
- Plaintext, US-ASCII encoding:
data:text/plain;,Hello World
- Plaintext, Base64 encoding:
data:text/plain;base64,SGVsbG8gV29ybGQ=
- HTML, US-ASCII encoding:
data:text/plain;,<h1>Hello World</h1>
- HTML, Base64 encoding:
data:text/html;base64,PGgxPkhlbGxvIFdvcmxkPC9oMT4=
- Plaintext, US-ASCII encoding:
data:,Hello World
Last updated on December 9, 2019