Improve page speed with data URLs and sass - part 4

SASS and data URLs

While the above methods works, they are error-prone and time-consuming. You need to manually update the CSS file when the images are changing.

If you use SASS you can use the following sass script with inline_image function extension. create a binsass.rb

binsass.rb - scss with inline-image extention 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
 header {
   background: inline-image("../img/header-bg.png");
 }

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

Data URI in CSS sample
 # ruby bin/sass.rb --update css

The main.css should be generated in css directory:

Data URI in CSS sample
 header {
   background : url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAIAAAAC64paAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAOwQAADsEBuJFr7QAAABl0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC4yMfEgaZUAAAAfSURBVDhPY/j+v49sNKqZRDSqmUQ0qplENPI0/+8DAOnW7m6FxOUUAAAAAElFTkSuQmCC');
 }

Summery

Data URLs can reduce the number of HTTP requests from the server, which may make the site faster and improve the page load time. We show what are data URLs, use cases and how can we generate them (manually and automatically via sass).