Best Data URL Usages [With 6 Samples]

Data URL is a special type URL that allows embedding small files inline in documents (HTML or CSS files). In this article, we see why you should use Data URL; we learn the format of this URL and see several usage samples; finally, we see how to generate Data URL manually and automate the process with SCSS.

Why To Use Data URL?

In the last years, sites have gradually become richer in functionality while demanding more network and device resources. Over the years, the experience shows that a faster site engages and retains users better than a slower one. As Google announced that site speed is used as a factor in their web search ranking algorithm, Site speed becomes even more essential and can be the difference between a successful site and a poorly performing one.

One way to make the site faster is to consolidate HTTP requests. As the number of HTTP requests from the browser increases, the overhead and load time of the site increases. Thus, when we combine several HTTP requests when possible (For example, consolidate several CSS files to one file), we can dramatically decrease the load time of our web pages.

What Is Data URL?

Data URL is special type URLs which allows embedding small files inline in documents(HTML or CSS files). The URL is prefixed with the data: scheme and have up to 3 parts.

Data URL Structure
 data:[<mediatype>][;base64],<data>
PartDescription
mediatypeThe mediatype is a MIME type string. For example, image/png for an image file in png format, image/jpeg for an image in jpeg format, image/svg for an image in svg format. If emitted text/plain;charset=US-ASCII will be used
base64Whether the encoding of the following data part is base64 and not text. Using this encoding, we can embed binary formats such as images in a text-based document. If this part is emitted, data is plain text which should use the appropriate entities or escapes based on the enclosing document
dataThe data
The parts of Data URL

Using Data URL In HTML

Sample 1 For Using Data URL In HTML – Embed Text File In Link

In the following sample, we embed a text file in a tag. When we click on the links, the browser will download a text file with the text file’s contents. The links have the same semantics, even though we emit the mediatype text/plain in first a tag.

Embed Text File In Link
<div>
  <a href="data:,I am text file" download="a1.txt">Download text file 1</a> </div>
<div>
  <a href="data:text/plain,I am text file" download="a2.txt">Download text file 2</a>
</div>
The Rendered HTML

Sample 2 For Using Data URL in HTML – Embed CSV file In Link

We can embed other media types besides text/plain media type. In the following example, we embed the text/csv mediatype in a tag. When we click on the link, the browser will download CSV file. Please, note how we use the URL encode to decode the newline character with %0A

Embed CSV file In Link
<div>
  <a href="data:text/csv,col1,col2%0A1,2%0A3,4" download="a1.csv">Download CSV file</a>
</div>
The Rendered HTML

Sample 3 For Using Data URL In HTML – Embed XML File in Link

In the following example we embed the text/xml mediatype in a tag. When we click on the link, the browser will download XML file.

Embed XML File in Link
<div>
  <a href="data:text/xml,<?xml version='1.0'?><note>I am an XML</note>" download='a1.xml'>Download xml</a>
</div>
The rendered HTML

Sample 4 For Using Data URL In HTML – Embed Images in HTML

We can also embed nontextual files in the HTML. In the following example, we see how we can embed image files in the src attribute of the img tag.

The mediatype of the image is image/png. The png format is binary and not text as we see in the above examples. Therefore, we encode the contents of the image in base64 encoding.

Embed Image File in img tag
<div>
 <img src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABl0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC4yMfEgaZUAAAAfSURBVDhPY/j+v49sNKqZRDSqmUQ0qplENPI0/+8DAOnW7m6FxOUUAAAAAElFTkSuQmCC' />
</div>
Rendered HTML

Sample 5 – Embed HTML in iframe

In the following example, we embed the text/html mediatype in iframe tag.

Embed HTML in iframe
<div>
  <iframe style='width:100%; height: 100px;background:#dddddd' src='data:text/html,<!DOCTYPE html><html><head></head><body><h1>Hello</h1><p>I am HTML</p></body></html>'></iframe>
</div>
The Rendered HTML

Using Data URL In CSS – Embed Images in CSS

You can also embed the data URL in CSS files. Using a data URL instead of an external URL to the image files decreases the number of HTTP requests and may improve the page speed.

Suppose we have the following CSS file:

CSS with External Image File
header {
  background : url('../img/header-bg.png')
}

Now, Let’s replace the external URL with a data URL. Since the image format is png, the image mediatype is image/png. As png is a binary format, we will use base64 encoding. So here how the new CSS file should be:

Embed Image File
header {
  background : url('data:image/png;base64,<binary data of the header-bg.png in Base64 Encoding>')
}

Let’s see how cam we encode the the contexts of the file in Base64 Encoding.

Encoding Binary Data in Base64 Encoding
with uuencode

If you have access to Linux machine, you can find the binary data via uuencode command. The binary data is located in the second line until ==== delimiter.

Encode file in base64 encoding with uuencode
# uuencode -m header-bg.png out
begin-base64 644 out
iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABl0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC4yMfEgaZUAAAAfSURBVDhPY/j+v49sNKqZRDSqmUQ0qplENPI0/+8DAOnW7m6FxOUUAAAAAElFTkSuQmCC
====

Encoding Binary Data in Base64 Encoding
with PHP

If you have access to PHP, you can find the binary data via the following command:

Encode file in base64 encoding with PHP
 # php -r "echo base64_encode( file_get_contents('header-bg.png')) ."\n";"
iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABl0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC4yMfEgaZUAAAAfSURBVDhPY/j+v49sNKqZRDSqmUQ0qplENPI0/+8DAOnW7m6FxOUUAAAAAElFTkSuQmCC

Automate with SCSS

We see how we can embed image files in CSS. While we can use the same manual actions, embed image files in SASS files are error-prone and time-consuming. You need to update the CSS file when the images are changing manually.

The following sass script provides the inline_image function extension. The inline_image function takes the path of the image file and automatically converts it to a data URL.

bin/sass.rb – SCSS With inline-image Extension Function
#!/usr/bin/env ruby
# The command line Sass parser.
require 'sass'
require 'sass/exec'
require 'mime/types'
require 'base64'

module Sass::Script::Functions
  def inline_image(path)
    path = File.join( File.dirname(environment.options[:filename]),path.value)
    data = File.open(path, 'rb') { |io| io.read }
    data64 = Base64.encode64(data).gsub("\n", '');
    mime   = MIME::Types.type_for(path)[0].content_type.force_encoding 'UTF-8'
    data_uri = "data:#{mime};base64,#{data64}"
    Sass::Script::String.new "url('#{data_uri}')"
  end
end

opts = Sass::Exec::SassScss.new(ARGV, :sass)
opts.parse!

Now Suppose your files in the CSS directory css/main.scss

Using the inline-image function in SCSS file
header {
  background: inline-image("../img/header-bg.png");
}

Now, to generate the CSS file, use the following command:

Generate the CSS file
 # ruby bin/sass.rb --update css
The Generated CSS
header {
background : url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABl0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC4yMfEgaZUAAAAfSURBVDhPY/j+v49sNKqZRDSqmUQ0qplENPI0/+8DAOnW7m6FxOUUAAAAAElFTkSuQmCC');
}

What is Data URL and Usage Samples – Movie Tutorial

What is Data URL and Usage Samples

Summary

We see what is data URL and why we should use them. We also see how to embed text files in HTML and how to embed binary files such as images in HTML and CSS. Then, we see how to manually encode files in base64 encoding. Finally we how to automate the process of embedding image files in CSS with the help SCSS.

Leave a Reply

Your email address will not be published. Required fields are marked *