Improve page speed with data URLs and sass - part 3

CSS and data URLs

The data URLs can also be used in CSS files. Using data URLs instead of external links to the image files decreases the number of HTTP requests and may improve the page speed.

Suppose we have the following CSS file:

Data URL in CSS sample #1
 header {
   background : url('../img/header-bg.png')
 }

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

Data URL in CSS sample #2
 header {
   background : url('data:image/png;base64,<binary data of the header-bg.png>')
 }

Finding the binary data via uuencode

If you have access to Linux machine, you can find the binary data via uuencode command

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

The binary data is located in the second line until ==== delimiter.

Finding the binary data via 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

In the next part we will see how can we embed images in CSS stylesheet with SASS