Automated Optimization with HTML5 Boilerplate Build
videos

Automated Optimization with HTML5 Boilerplate Build

Tutorial Details
  • Topic: HTML5 Boilerplate
  • Version: 0.95
  • Difficulty: Intermediate
  • Estimated Completion Time: 30 min

HTML5 Boilerplate is widely recognized as a rock-solid foundation for building new web-based sites and applications. That said, few are aware that the tool offers more than simply setting up your development environment. It also helps you “wrap up” your work by providing an awesome cross-platform build process.


The Build Script, with Paul Irish


Overview

So why might you need this build tool? Because it’s baked into HTML5 Boilerplate, and can help you automate web performance optimization. We chose to go with Apache Ant to handle the workload. How come?

All other tools have limitations that Ant’s original author couldn’t live with when developing software across multiple platforms.

Many developers are unfamiliar with the build process. But don’t worry; a build tool isn’t a scary monster. Everything can be configured through a relatively simple XML file. This article will help you understand how to set up the build tool, customize the build process and finally change variables and run the build.


The Directory Structure

The build script makes some assumptions about how your files are sorted and structured. Here is the folder structure of HTML5 Boilerplate:

Tutorial image
  • /js/libs/ – contains common script libraries: Modernizr, jQuery and a pngfix for IE6
  • /js/mylibs/ – contains site specific custom library scripts
  • /plugins.js – all jQuery plugins
  • /script.js – site/page specific JavaScript

The Build Folder Structure

The build/ folder contains the following elements:

build.xml

Apache Ant’s build files are written in XML. This file contains our project (Boilerplate Build) and targets. Targets contain task elements. Each task element of the buildfile can have an id attribute and can later be referred to by the value supplied to it, which must be unique.

default.properties

default.properties contains the default build options, project structure and hardcore build options, which we’ll review shortly.

build.properties

This file defines overrides for default.properties. This should be created by a user when he or she needs to override particular values. Consequently, it should not be placed under version control.

tools

Tools are a set of bundles, which include opyipng, JPEGTran, YUI compressor and HTML compressor.


Set up the Build Tool

Because the goal of the build tool is to be platform agnostic, we’ll review the necessary steps to set it up, dependent upon your OS of choice.

  • Windows – Grab and install WinAnt.
  • Mac OSX – Using homebrew, install the following packages: brew install libjpeg optipng. With MacPorts, use the following install command: port install jpeg optipng
  • Ubuntu (Linux) – Using apt, install the following packages: apt-get install libjpeg-progs optipng

Walkthrough of the buildfile

The build tool is nothing more than an XML file that is based on Apache Ant. Below is a walk through of the pre-defined build process. These elements can be configured by editing the build.xml file.

Concatening / Minifying JavaScript

<!-- Optimize javascript files -->
<target name="js.all" depends="js.remove.console, js.all.min, js.main.concat, js.libs.concat, js.concat.scripts, 
js.minifyonly.min, js.delete"></target>
<!--  JS: Concat primary scripts -->

...

<!-- JS, Delete concatenated libs file (only if concat.scripts and delete.unoptimized are defined) -->
<target name="js.if.concat.scripts" if="build.delete.unoptimized, build.concat.scripts">
	<delete file="./${dir.publish}/${dir.js}/libs-${build.number}.min.js"/>
	<delete file="./${dir.publish}/${dir.js}/scripts-${build.number}.min.js"/>
</target>
  • The /js/libs/ files are minified, but not concatenated. Modernizr should be alone in the head of the document. jQuery might be pulled from a CDN, and the pngfix will be included for IE6 only.
  • /js/mylibs/ contains your other various JavaScript libraries and plugins. All files stored here here will be minified (unless they end with .min.js), and then concatenated together.
  • plugins.js and script.js, in the /js/ folder, are all yours. These will also be minified and concatenated with the mylibs/ files.

Minifying CSS

<target name="css" depends="copy">
    <echo message="Minifying css..."/>
    <concat destfile="./${dir.publish}/${dir.css}/style-${build.number}.css">
     <fileset file="./${dir.css}/style.css"/>
    </concat>
    ...
</target>

All CSS files are minified using YUI compressor. The above Ant script will run style.css through YUI compressor for minification.

Image Optimization

<target name="imagespng" depends="copy">
	<echo message="Optimizing images"/>
    <apply executable="optipng" osfamily="unix">
     <arg value="-o7"/>
     <fileset dir="./${dir.publish}/">
       <include name="**/*.png"/>
     </fileset>
    </apply>
    ...
</target>

In HTML5 Boilerplate, we chose to use OptiPng and jpegtran for image optimization for PNG and JPG images, respectively. That said, there are plenty of image optimization tools. Should you wish to do so, you’re free to replace the tools with your own favorite image optimization tools.

For instance, Smush.it uses ImageMagick to identify the image type and convert GIF files to PNG files. It then uses gifsicle to optimize GIF animations by stripping repeating pixels in different frames.

Removing Development-Only Coding

<exclude name="**/${dir.js}/profiling/**"/>
<exclude name="**/${dir.test}/**"/>
...
<target name="js.remove.console" description="Comment out console.log lines">
	<echo>Commenting out console.log lines</echo>

	<replaceregexp match="(console.log\(.*\))" replace="/\*\1\*/" flags="g" >
		<fileset dir="./${dir.publish}/${dir.js}/">
			<include name="**/*.js"/>
			<exclude name="**/*.min.js"/>
		</fileset>
	</replaceregexp>  
		
</target>

Files like console.log, profiling and unit testing files are not needed for the release of the site.

Minifying HTML

<target name="htmlbuildkit" depends="html" >

<apply executable="java" parallel="false" force="true" dest="./${dir.publish}/" >
     <fileset dir="./${dir.publish}/" includes="*.html"/>
     <arg value="-jar"/>
     <arg path="./${dir.build}/tools/htmlcompressor-0.9.3.jar"/>

</apply>
</target>

Listed below are some various options for minifying your HTML files:

  • htmlbuildkit – Preserves comments, multiple spaces and compresses inline JavaScript and CSS.

  • htmlclean – Preserves multiple spaces, removes unneeded quotes and compress inline JavaScript and CSS

  • htmlcompress – Removes unneeded quotes and compresses inline JavaScript and CSS.

Automated Baseline Numbering / Cache Busting

HTML5 Boilerplate uses query string for JavaScript/CSS versioning and cache busting.

HTML5 Boilerplate by default uses query string for JavaScript/CSS versioning and cache busting. The drawback with this approach is that some intermediate proxies – and potentially other clients – may not cache assets that contain query strings. This is due to basic heuristics that flag such requests as dynamic data.

The build tool will first remove the query string versioning and use automated baseline numbering for release control and cache busting.

Configuring Excludes

<exclude name=".gitignore"/>
<exclude name=".project"/>
<exclude name=".settings"/>
<exclude name="README.markdown"/>
<exclude name="**/.git/**"/>
<exclude name="**/.svn/**"/>
<exclude name=".gitignore"/>
<exclude name="*.conf*"/>
<exclude name="mime.types"/>
<exclude name="**/${dir.build}/**"/>
<exclude name="**/${dir.test}/**"/>
<exclude name="**/${dir.demo}/**"/>
<exclude name="**/${dir.js}/profiling/**"/>

Not all files will need to be published. A perfect example of this would be files generated by versioning control system like subversion and git.

By default, there is a list of file types and directories that will be excluded. To add to this list, you can search and find <!-- configurable excludes --> and append your custom exludes to it.


Walkthrough of default.properties

Variables inside the build file are defined in default.properties and build.properties.

Build options

  • build.concat.scripts = true – If set, multiple script files will be smushed together to a single, cohesive file.
  • build.delete.unoptimized = true – If set, unoptimized files will be deleted.
  • file.exclude = nonexistentfile – Excludes file filter for publishing (can’t be empty).

Project Structure

dir.publish	= publish
dir.build	= build
dir.tools	= ${dir.build}/tools
dir.test	= test
dir.demo	= demo
dir.js		= js
...

The project structure contains directory names, like the ones shown above, as well as the core JS folder, JS utility libraries, and folders which should only be minified but not concatenated.

Other Build Options

  • build.info = buildinfo.properties – Build versioning is defined
  • tool.yuicompressor = yuicompressor-2.4.2.jar – YUI Compressor is defined with yuicompressor-2.4.2.jar

Okay – But How Do I Use This?

Finally, we’ll learn exactly how you can use the build tool in your projects! Refer to the following steps to run the build tool.

  • Open a command line interface, and navigate to your project folder.
  • Navigate into the build folder: cd build/
  • There are four different ways to build your site: the default way is: ant build
  • When the build script changes your HTML to reference the new minified script (usually named something like scripts-002.min.js), it looks for some HTML comments which refer to the beginning and end of the script block. Currently, it looks for <!– scripts concatenated and <!– end concatenated and minified scripts–>.

Build Options

Here’s a list of various build options that you can choose from to suit your particular need:

  • ant build – minor html optimizations (extra quotes removed). inline script/style minified (default)
  • ant buildkit – all html whitespace retained. inline script/style minified
  • ant minify – above optimizations plus full html minification
  • ant text – same as build but without image (png/jpg) optimizing

Conclusion

Performance optimization doesn’t have to be expensive or time consuming. With some reusable rules, one can slowly setup a build process to automate the repetitive aspects of optimization work. Apache Ant provides a powerful, yet easy to use, framework, while HTML5 Boilerplate leverages that to make web optimization as easy as possible for front-end web developers. Thank you so much for reading!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://hubersen.ch hubeRsen

    Nice read. One hint: the link to html5boilerplate at the beginneng is missing the “L” of html. ;-)

  • Wouter

    You’re link to HTML5 boilerplate is wrong. The site http://www.htm5boilerplate.com/ don’t exist.
    I think you mean http://www.html5boilerplate.com/ (the difference is html in the place of htm).

    This is also a good tutorial! I always will minify CSS/JS.

  • http://youssefboubdir.me.gp Youssef Boubdir

    Build scripts helps me a lot to save time
    Here is a video presentation by Paul Irish http://bit.ly/g9M3XJ

  • Sitebase

    Ant is a great tool that can save you a lot of time. Learn to use it and you’ll love it.

    • Christian Sciberras

      Ant is one huge mess. I’ve used, and still use it. I’ll do anything to throw it away for a better alternative.

      • Markus

        You are absolutely right, I hoped that I never had to see something like Ant again – but perhaps those guys from html5boilerplate didn’t know better build systems.

        In this developers more experienced than designers, we should forgive them.

        I set up my own scripts for sure :)

  • bob

    whats about php files with html ….how can i compress the html?

  • David Runion

    Wow, great tutorial, you really covered this well and made me want to use the technology.

    Also, extra points for having a non-English name but excellent grammar!

  • Ed Moore

    Nice tut Shi Chuan. I’ll try and use the build script for my next project.

  • http://www,blog.highub.com Shi Chuan
    Author

    We have just released boilerplate version 1.0 recently, so there has been significant update since then, here is the updated tutorial by Paul http://www.youtube.com/watch?v=OXpCB3U_4Ig&feature=player_embedded

  • http://itcutives.com Jatin

    I am experimenting with HTML5 Boilerplate since its inception. With the latest version (v1.0), released on 21st March, I do see lot’s of optimization in code itself.

    About this article, I must say, Shi Chuan (author) has brilliantly explained the optimization part with HTML5 Boilerplate.

    It’s my personal recommendation to web-development community to go for HTML5 Boilerplate, and help community to improve it further.

  • Wayne

    I was taking a look at this video the other day and was hoping for a more comprehensive tut on this! Great stuff, can’t wait to get stuck into this!

  • http://www.mattjura.com Matt Jura

    For those of you that are working with DotNetNuke here is the plate adapted for DNN http://www.mattjura.com/home/post/62/dotnetnuke-html5-boilerplate-skinning-file-set.aspx – big thanks for the effort to all working on the HTML5 Boilerplate project :)

    • http://itcutives.com Jatin

      HTML5 BoilerPlate + DotNetNuke = Awesome Friends

      • Jason

        DNN = POS

  • http://www.potte.com web design

    wow thats nice stuff informative points

  • Clyde Sanchez

    Wow, that is some really powerful stuff. I am always looking for ways to optimize my WordPress themes (without the use of plugins, if possible), which leads me to the following question:

    How can I implement this into WordPress? Would the build script be at the root of the WordPress install, or would it make more sense to put it in the theme?

    Again, I really like the script, it should save lots of time for me in current and future projects!

  • Paul

    I have not tried html5-boilerplate. But after this read, I will definitely give it a shot.

  • http://designfromwithin.com/ DESIGNfromWITHIN

    I use HTML5 Boilerplate with the great MODx CMS.

    On my blog I created a 2 part video tutorial about it:
    Using the fantasic MODx Boilerplate – part 1
    Using the fantasic MODx Boilerplate – part 2

  • http://fzy.co Ersin Demirtas

    Thanks, very helpful.

  • http://www.goldweb.lt/ http://www.goldweb.lt/

    New way to build great HTML document, this standard to new beauty of web design.

  • http://net.tutsplus.com/tutorials/html-css-techniques/automated-optimization-with-html5-boilerplate-build/ angel

  • http://www.shtigliz.com ron

    someone please help!!
    i have my own mvc that i use html5boilerplate with, and it works great
    untill i try the build script.
    none of the minifications work and none of the optimizations.
    all my asstests are in the assets folder like so:
    assets -> css
    ->js
    ->images
    ->and other folders.

    so in the project.properties i list the css files i want to minify
    like so:
    file.stylesheets = main.css,tablet.css,mobile.css,nivo-
    slider.css,prettySociable.css,validationEngine.jquery.css

    and
    file.pages = templates/main.tpl,maintenance.tpl

    and
    dir.css = assets/css

    then i run the bat file, or using ant . the publish folder does exists
    but no minification and no optimization.

    what am i missing ?

    best regards

  • http://www.twitter.com/fgaeg fgaeg

    At the first time, just curious how to use “Build” folder on h5bp. But now, I’ve got an answer by this h5bp post and it’s quite helpfull for me xD

    Thanks, the web really need this :)

  • Paolo

    ant requires 105mb to install? is that right?

  • Sarvesh

    Awesome…

  • John

    great stuff as always! just wondering if I’m missing a step here because only my first HTML file gets compressed not the other HTML pages. CSS and JS compress fine though…

    • Ian

      I’m trying to figure out the same thing. I have a site with about 10 html pages and only the first one gets built with ant. They all use the same css and common js files but after build only the first page works because the css and js have been concatenated.

      John if you figure this out can you post it and I’ll do the same.

      • Ian

        Well that was easy. Go into the config/project.properties file and set

        file.pages = *.html

        to hit all html files.

        I haven’t tested anything but the ‘build’ target yet but ‘build’ worked perfectly changing css and js links and removing comments in all html files and the site is working perfectly.

  • http://www.joewatts.co.uk Joe Watts

    Does anyone know if it is how or if it is possible to add includes?
    For example I would like to have the navigation in 1 file and include it in every html file like I would in php. Can it be set up to do this when the build script is ran and if so what tags do I use?

  • German Zargaryan

    For commenting console.log statements I used following modification of above mentioned script:

    Commenting out console.log lines

    This one can handle also statements like this console.log(1,2,3);

  • German Zargaryan

    For commenting console.log statements I used following modification of above mentioned script:

    <target name=”-js.remove.console”
    description=”Comment out console.log lines”>
    <echo>Commenting out console.log lines</echo>
    <replaceregexp match=”(console\.log\(.*?)\);?,?”
    replace=”/\*\1\*/”
    flags=”g”>
    <fileset dir=”./${dir.publish}/${dir.js}/”>
    <include name=”**/*.js” />
    <exclude name=”**/*.min.js” />
    </fileset>
    </replaceregexp>
    </target>

    This one can handle also statements like this console.log(1,2,3);

    • http://web-on-a-nutshell.com jatazoulja

      hmmm I was hoping to delete more than just the log… (console.trace, console.debug etc. etc… :D )
      would this do the trick:

      console\.log|trace|debug|etc\ ???

  • http://web-on-a-nutshell.com jatazoulja

    hmmm for some reason its not loading the default.properties or the project.properties so I had to modify by adding

    <property environment=”ENV” />
    <property name=”dir.source” value=”htdocs”/>
    <property name=”dir.js” value=”js”/>
    <property name=”dir.css” value=”css”/>
    <property name=”dir.images” value=”img”/>
    <property name=”dir.publish” value=”publish”/>
    <property name=”dir.intermediate” value=”intermediate”/>
    <property name=”file.root.stylesheet” value=”style.css”/>
    <property name=”dir.build.tools” value=”${basedir}/h5bp-ant-build-script-51b41f7/tools”/>
    <property name=”tool.yuicompressor” value=”yuicompressor-2.4.7.jar”/>
    <property name=”hash.length” value=”7″/>
    <property name=”file.root.page” value=”index.html”/>
    <property name=”file.root.script” value=”main.js”/>

    any Idea why?!

  • http://dlme.ir script

    Awesome things here. I’m very happy to peer your article. Thank you a lot and I’m having a look ahead to contact you. Will you kindly drop me a e-mail?