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 =, 'rb') { |io| }
     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}" "url('#{data_uri}')"

 opts =, :sass)

Now Suppose your files in the CSS directory

 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 {


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