File Size Optimization
config.rb, activate the
during the build of your site.
If you are already using a compressed file that includes
.min in its
filename, Middleman won't touch it. This can be good for libraries like jQuery
which are carefully compressed by their authors ahead of time.
:compressor option for the
config.rb to a custom instance of Uglifier. See Uglifier's docs
For example, you could enable unsafe optimizations and mangle top-level variable names like this:
If you have
asset_hash activated, are building your site on multiple servers
ensure that mangling variables is disabled. If mangling is enabled, Uglifier
leading to different hashes in the filename and different references in each
version of the HTML. For example:
If you want to exclude any files from being minified, pass the
when activating these extensions, and give it one or more globs, regexes, or
procs that identify the files to ignore. Likewise, you can pass an
option to change which file extensions are renamed.
including these gems in your
gem 'therubyracer' # faster JS compiles gem 'oj' # faster JS compiles
gzip text files
It's a good idea to serve compressed files to user agents
that can handle it. Many web servers have the ability to gzip files on the fly,
but that requires CPU work every time the file is served, and as a result most
servers don't perform the maximum compression. Middleman can produce gzipped
you can instruct your web server to serve those pre-gzipped files directly.
First, enable the
If you also want to compress images on build, try middleman-imageoptim.
Middleman provides an official extension for minifying its HTML output. Simply
middleman-minify-html to your
bundle install, open your
config.rb and add:
You should notice whilst view-source:'ing that your HTML is now being minified.
Responsive images with
One of the more recent additions to HTML is the
srcset attribute for the
picture tag. It allows you to define for the browser to load different
images with different sizes dependent on either the viewport (using width such
1024w, 800w, 600w, or 320w) or the resolution of the current browser
display (using factors
1x, 2x, 3x, ...).
<img src="img/100px.jpg" srcset="img/300px.jpg 3x, img/200px.jpg 2x, img/100px.jpg 1x"> <img src="img/100px.jpg" srcset="img/300px.jpg 300w, img/200px.jpg 200w, img/100px.jpg 100w">
If you want to use
srcset in conjunction with the
:asset_hash option, you
need to employ the
<img src="<%= image_path('100px.jpg') %>" srcset="<%= image_path('300px.jpg') %> 3x, <%= image_path('200px.jpg') %> 2x, <%= image_path('100px.jpg') %> 1x">
srcset attribute is not yet supported by all browsers as you can see at
Can I Use. If it is not supported, the browser uses the
src attribute as
a fallback. We noted, that some browsers use the first entry of the
a fallback. This is why we have put the largest image first in our example.