Getting Started Using HTML5 Boilerplate
Get to know a handy resource for web developers that simplifies the process of writing HTML5-compliant web pages
July 25, 2011
Whether we like it or not, HTML5 is all the rage now days. With Windows 8's support for HTML5 and JavaScript, the hype has intensified even more. I'm personally in favor of what HTML5 brings to the table (see "Start Using HTML5 in Your Web Apps - Today!" for more information), although I do worry about browser compatibility issues that will naturally crop up. Compatibility issues are something that web developers have been dealing with since the days of Netscape 4 (layers) and Internet Explorer 4 (divs), though, so it's really nothing new; it's just intensified with all the new functionality that the various HTML5 specs define. Fortunately, several options are available that can help reduce cross-browser issues.
Getting started building HTML5-compatible sites can be challenging, especially for people who haven't been involved in web development projects for a while. Fortunately, there are a few sites available that greatly simplify the process of getting started building HTML5 websites and offer some excellent "boilerplate" code that can help both new and experienced web developers. One of the best ones out there is called HTML5 Boilerplate, and others exist—such as initializr.com (which is based on HTML5 Boilerplate). The creators of the HTML5 Boilerplate site (including JavaScript guru Paul Irish from the jQuery and Google Chrome teams) define the functionality offered by HTML5 Boilerplate in the following way:
"HTML5 Boilerplate is the professional badass's base HTML/CSS/JS template for a fast, robust, and future-proof site. After more than three years in iterative development, you get the best of the best practices baked in: cross-browser normalization, performance optimizations, even optional features like cross-domain Ajax and Flash. A starter apache .htaccess config file hooks you the eff up with caching rules and preps your site to serve HTML5 video, use @font-face, and get your gzip zipple on. Boilerplate is not a framework, nor does it prescribe any philosophy of development, it's just got some tricks to get your project off the ground quickly and right-footed."
Figure 1: HTML5 Boilerplate options
Features offered in HTML5 Boilerplate include cross-browser compatibility (they deal with IE6, IE7, and IE8 in a clever way); inclusion of caching and compression rules; utility classes such as .no-js and .clearfix; .png support in IE6; Modernizr support; Google analytics support; mobile browser optimizations; IE-specific classes for maximum cross-browser control; JavaScript profiling and testing support; and CDN-hosted jQuery with a local fallback script—plus quite a bit more. When you visit the HTML5 Boilerplate site, you're presented with three options, as shown in Figure 1: Boilerplate Documented, Boilerplate Stripped, and Boilerplate Custom.
If you select Boilerplate Documented, you'll get a .zip file with the skeleton code needed to get started building an HTML5 site, including documentation, built-in jQuery CDN support, CSS, caching, and more. Boilerplate Stripped contains the same HTML/CSS/JS but removes comments, and Boilerplate Custom allows you to build a custom site skeleton and control what gets added or removed. Figure 2 shows an example of the custom options that can be selected.
Figure 2: HTML5 Boilerplate custom options
What's in HTML5 Boilerplate?
If you select the documented or stripped options, you'll get a .zip file that contains an HTML5 skeleton to help jumpstart your web development. Figure 3 shows what the site structure looks like.
Figure 3: HTML5 Boilerplate project files and folders
Looking through the folders, you'll see that they contain CSS, JavaScript, and HTML files as well as favicon.ico, crossdomain.xml for Flash and Silverlight, a 404.html page, robots.txt for search engines, and QUnit testing functionality.
CSS Support
Two CSS files are included out of the box: the main CSS file used by the site, named style.css, and a starter script for hand-held devices, named handheld.css. The style.css file includes several different tips, tricks, and best practices that can be used to handle rendering HTML across multiple browsers (including IE6). It adds in some clever features, such as hiding content from a page and ensuring the content doesn't take up any space while still making it available to screen readers. Figure 4 shows an example of a CSS class named visuallyhidden that performs the screen reader trick.
/* Hide only visually, but have it available for screenreaders: by Jon Neal. www.webaim.org/techniques/css/invisiblecontent/ & j.mp/visuallyhidden */.visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; }/* Extends the .visuallyhidden class to allow the element to be focusable when navigated to via the keyboard: drupal.org/node/897638 */.visuallyhidden.focusable:active,.visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; }
The style.css file also includes the popular clearfix solution that can be used to prevent margins from collapsing on child elements when the children are floated. If you've ever written HTML and CSS where you floated children left or right, then had to add a final child with "clear:both" in the style to make things look right, you'll find that this fix greatly simplifies the process since you can simply apply the clearfix class, as the code in Figure 5 shows.
/* The Magnificent Clearfix: Updated to prevent margin-collapsing on child elements. j.mp/bestclearfix */.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; }.clearfix:after { clear: both; }/* Fix clearfix: blueprintcss.lighthouseapp.com/projects/15318/tickets/5-extra-margin-padding-bottom-of-page */.clearfix { zoom: 1; }
Print styles are also included to simplify the process of removing backgrounds, handling links, printing table rows, handling images, and more, as shown in Figure 6.
/** * Print styles. * * Inlined to avoid required HTTP connection: www.phpied.com/delay-loading-your-print-css/ */@media print { * { background: transparent !important; color: black !important; text- shadow: none !important; filter:none !important; -ms-filter: none !important; } /* Black prints faster: sanbeiji.com/archives/953 */ a, a:visited { color: #444 !important; text-decoration: underline; } a[href]:after { content: " (" attr(href) ")"; } abbr[title]:after { content: " (" attr(title) ")"; } .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } /* Don't show links for images, or javascript/internal links */ pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } /* css-discuss.incutio.com/wiki/Printing_Tables */ tr, img { page-break-inside: avoid; } @page { margin: 0.5cm; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3{ page-break-after: avoid; }}
Moving into the js folder in the project, you'll find jQuery, IE6 .png support, and Modernizer scripts included in the js/libs folder. Custom scripts can go in the scripts.js file, and plug-in scripts can go in plugins.js. Any custom libraries used in the site can go in the mylibs folder. Keep in mind that the folders are only a recommended folder structure, and as the HTML5 Boilerplate site likes to say, all the code is "delete-key friendly," so feel free to reorganize things to fit your needs.
The index.html File
When you open the index.html file provided by HTML5 Boilerplate, you'll find some interesting code right at the top, as shown next:
<!doctype html><!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ --><!--[if lt IE 7 ]> <html class="no-js ie6" lang="en"> <![endif]--><!--[if IE 7 ]> <html class="no-js ie7" lang="en"> <![endif]--><!--[if IE 8 ]> <html class="no-js ie8" lang="en"> <![endif]--><!--[if (gte IE 9)|!(IE)]><!--> <html class="no-js" lang="en"><!--<![endif]-->
First, you'll note that the standard HTML5 doctype declaration is defined. I can't tell you how happy it makes me to have this simple definition since the different XHTML doctype options were hard to remember. Immediately under the doctype you'll notice the inclusion of several conditional statements to check for IE6, IE7, IE8, and IE9 along with other modern browsers. By default this code adds a no-js CSS class name and the appropriate IE class on the root <html> element if Internet Explorer is hitting the site. If another browser such as Chrome or Firefox is hitting the page, then only the no-js class is added to the <html> element. The no-js class is used to handle browsers that don't support JavaScript. For example, if you wanted to hide all <h1> elements in the page when a browser doesn't support JavaScript, you could add the following definition into style.css:
.no-js h1 { display: none; } /* Hide h1 tags if Javascript is disabled */
At this point, you may wonder how the no-js class gets removed from the <html> element when a browser does support JavaScript. After all, if the browser supports JavaScript, it wouldn't make much sense to have a no-js class defined. To handle this situation, the HTML5 Boilerplate code adds a reference to the Modernizr script within the head section of index.html:
<script src="js/libs/modernizr-1.7.min.js"></script>
By default, Modernizr will locate the <html> element and change no-js to js if JavaScript is supported by the browser. Figures 7 and 8 show an example of how Modernizr modifies the <html> element; the example in Figure 7 uses the IE9 developer tools (press F12 when viewing a site in IE9 to get to the developer tools), and the Figure 8 example uses the Chrome developer tools (Ctrl+Shift+I).
Figure 7: Viewing the element using the IE9 developer tools
Figure 8: Viewing the element using the Chrome developer tools
HTML5 Boilerplate's index.html page includes several other interesting features, such as the meta tags shown in Figure 9.
<meta charset="utf-8"><!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame. Remove this if you use the .htaccess --><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
The first meta tag sets the character set to utf-8 and is a shorthand version of what was used previously in web pages:
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
At first glance, setting the character set may seem trivial and unimportant, but it can actually stop some script attacks that rely on utf-7, so it's recommended that you define it in your pages. The second meta tag shown in Figure 9 is used to force Internet Explorer to use its most modern rendering engine. This comes into play with IE8 and IE9 since they have compatibility modes that a user can select in the address bar and ensures that Internet Explorer compatibility mode rendering isn't used (even if the user selected it). Although this second meta tag doesn't pass the latest W3C validation test, it's good to have to prevent IE8/IE9 browsers from reverting back to IE7 mode due to the user enabling compatibility mode.
Moving down further in the <head> element within index.html, you'll see that Google's Content Delivery Network (CDN) is used to load jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
This provides several benefits related to caching and location. A user visiting a site that references the Google CDN URL for jQuery will have the script cached in their browser. If they then visit your site that references the same CDN script file, the cached version will be used, resulting in faster page load times. Also, Google's CDN servers (note that Microsoft also provides a CDN for jQuery) are located throughout the world, so when the jQuery script gets loaded for the first time, a server close to the user's location will normally be hit.
Having a reference to the CDN version of jQuery is nice, but it's always good to have a fallback in case the CDN is inaccessible for any reason. HTML5 Boilerplate uses a trick I like to use as well to embed a local copy of jQuery if the CDN version can't be loaded. It does so by checking for the existence of the window.jQuery object. If the object isn't found, then the CDN script wasn't loaded successfully and a local version of the script is loaded instead:
<script>window.jQuery || document.write("<script src='js/libs/jquery-1.5.1.min.js'>\x3C/script>")</script>
Another key item added into index.html is a reference to the Google Analytics script for tracking page hits and other details. If you have a Google Analytics account, you can update your site's ID in the provided script:
<script> var _gaq=[["_setAccount","UA-XXXXX-X"],["_trackPageview"]]; (function(d,t){var g=d.createElement(t), s=d.getElementsByTagName(t)[0];g.async=1; g.src=("https:"==location.protocol?"//ssl":"//www")+ ".google-analytics.com/ga.js"; s.parentNode.insertBefore(g,s)}(document,"script")); </script>
Testing Features
In addition to the HTML, CSS, and JavaScript features added by HTML5 Boilerplate, support for QUnit is also included out of the box. QUnit is a JavaScript test library used to test the Query project code but can also be used to test JavaScript code that you write. Within the project created by HTML5 Boilerplate, you'll find a folder named test that contains the qunit.js and associated CSS file as well as a sample test HTML page and test script. The test script provides a few basic examples of using QUnit to perform assertions and test logging functionality available in the plugins.js file included with the project (see Figure 10). A complete discussion of QUnit is outside the scope of this article, but you can read more about it on the jQuery QUnit page.
module("example tests");test("HTML5 Boilerplate is sweet",function(){ expect(1); equals("boilerplate".replace("boilerplate","sweet"),"sweet", "Yes. HTML5 Boilerplate is, in fact, sweet"); })// these test things from plugins.jstest("Environment is good",function(){ expect(3); ok( !!window.log, "log function present"); var history = log.history && log.history.length || 0; log("logging from the test suite.") equals( log.history.length - history, 1, "log history keeps track" ) ok( !!window.Modernizr, "Modernizr global is present")})
HTML5 Jumpstart
Whether you're an experienced web developer or someone looking to get into HTML5 web development, the code generated by the HTML5 Boilerplate site can help jumpstart your projects and also serve as a good learning environment. HTML5 Boilerplate includes several tips and tricks to handle cross-browser issues that crop up, implements proven best practices, and ultimately simplifies the process of writing HTML5-compliant web pages. Although the code generated by HTML5 Boilerplate only provides skeleton HTML/CSS/JS code, you can visit other sites such as initializr.com that build on the skeleton code while supplying functional pages with graphics and placeholders. Now I invite you to join me in "Build a jQuery HTML5 Web Application: The Account at a Glance," where I'll show you a sample application that demonstrates why it's essential to get comfortable with HTML5 and jQuery so you can create your own leading-edge business applications.
About the Author
You May Also Like