前言:

整理文章的时候发现草稿里躺着这样一篇文章——竟然是三年前的了,光阴飞逝啊!Html5 Boilerplate 看似简单,实则是前端优化的集大成者,每个前端开发者都应该仔细阅读其代码,包括注释里的一些链接,你将会受益匪浅。Divya Manian 还写了一本 HTML5 Boilerplate Web Development 专门介绍这个前端模板,有兴趣的朋友可以搜一下,网上能找到电子书(找不到找我要也行)。

正如上面所说,这是三年前的文章。时过境迁,Html5 Boilerplate 当前版本(4.20)中已经更新改进了许多代码,比如说 CSS reset 样式已经被弃用,改为使用 normalize.css ,使用时请以最新版本为准。


和许多网页设计师和开发者一样,我最近发现一个不可思议的资源,由网页开发工程师 Paul Irish 和Divya Manian 收集整理。Html5 Boilerplate,正如其名,是任何网站、网页应用程序强大的开端。正如Paul Irish所言:其本质上是一个HTML和CSS初始模板和目录结构,更是几年来前端开发的最佳实践。

即便你不想把Html5 Boilerplate作为基础模板,它里面也包含许多不可思议的非常值得使用的代码段。

HTML

我们将首先挑选出一些资源中使用的html代码片断。 这些都不完全是 html,但如果使用的话都要放置在html文件中。

Favicon and Apple icons

Favicon已经很常见了,apple-touch-icon则比较有趣,如果把网站书签添加到苹果触摸设备(如iPad、iPhone)的首页,apple-touch-icon就会显示在上面。有意思的是,Android也使用它。目前而言,apple-touch-icon的尺寸是60px * 60px。据网友留言,如果图标放在根目录的话,则无需定义这些链接。
<!-- Place favicon.ico and apple-touch-icon.png in the root of your domain and delete these references -->
<link rel="shortcut icon" href="/favicon.ico">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">

提高页面载入速度技巧

这个空的注释语句主要用来提高网站的载入速度。如果网站中使用了条件注释(例如针对IE6的条件样式表),条件注释将阻止其它文件下载,直到CSS文件下载完成为止,致使页面载入速度降低。为解决这个问题,只需在文档中载入CSS链接的前面添加像下面的空条件注释。更多详情请查看Conditional comments block downloads
<!--[if IE]><![endif]-->

 X-UA-Compatible

Internet Explorer 有许多解析引擎提供使用。IE=edge强制IE使用最新可用的解析引擎。接下来是chrome=1:Chrome Frame是一个IE6-8的插件,可以让IE使用Google Chrome的解析引擎。如果用户安装了这个插件,网站就会调用Chrome引擎来解析。更多Chrome Frame的信息,及若用户没有安装这个插件时如何提示其安装, check here
<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

 条件body标签

这个代码片段是Paul Irish原创的,用来为不同版本的IE浏览器设定不同的CSS样式,而无需增加额外的HTTP请求样式表。基本上,根据用户使用的IE浏览器版本,给body标签添加一个对应的类。如果用户使用非IE浏览器,则使用没有类的body标签。这样就可以为特定的浏览器编写样式,无需CSS hack或者而外的样式表。更多详情,请查看Conditional stylesheets vs CSS hacks? Answer: Neither!
<!--[if lt IE 7 ]> <body class="ie6"> <![endif]-->
<!--[if IE 7 ]> <body class="ie7"> <![endif]-->
<!--[if IE 8 ]> <body class="ie8"> <![endif]-->
<!--[if IE 9 ]> <body class="ie9"> <![endif<]-->
<!--[if (gt IE 9)|!(IE)]><!--> <body> <!--<![endif]-->

 预留jQuery载入退路

现在许多网站都在使用jQuery JavaScript库。许多网站使用托管在Google服务器中的jQuery库以获得更快的载入速度和更好的跨站点缓存。但是如果服务器故障、jQuery无法从Google载入呢?下面就是预留的退路:检查jQuery是否从Google载入,如果没有,则载入本地服务器上的版本。
<!-- Grab Google CDN's jQuery. fall back to local if necessary -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>!window.jQuery && document.write('<script src="js/jquery-1.4.2.min.js"></script>')</script>

优化Google Analytics

Google Analytics是一个很受欢迎的跟踪用户行为、访问的工具。下面是优化的Google异步跟踪的代码,优化细节以查看此文 Optimizing the asynchronous Google Analytics snippet
<!-- asynchronous google analytics
change the UA-XXXXX-X to be your site's ID -->
<script>
 var _gaq = [['_setAccount', 'UA-XXXXX-X'], ['_trackPageview']];
 (function(d, t) {
  var g = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
  g.async = true;
  g.src = '//www.google-analytics.com/ga.js';
  s.parentNode.insertBefore(g, s);
 })(document, 'script');
</script>

 CSS

下面是CSS,都是悉心发现的一些代码片段。不要小视那些只有一行的代码,它们和那些稍大的代码片段一样有用,一样了不起。

支持Html5的CSS reset

在此之前,很多用户已经在使用Eric Meyer’s css reset了。它被包含在许多框架中,诸如960.gs,等等。下面是一个全面支持HTML 5的修订版本。它将所有新的结构元素设置为块级,并重置默认的样式。
/*&nbsp;&nbsp;&nbsp;html5doctor.com Reset Stylesheet (Eric Meyer's Reset Reloaded + HTML5 baseline)&nbsp;&nbsp;v1.4 2009-07-27 | Authors: Eric Meyer & Richard Clark&nbsp;&nbsp;html5doctor.com/html-5-reset-stylesheet/*/
html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, figure, footer, header,&nbsp;hgroup, menu, nav, section, menu,
time, mark, audio, video {
margin:0;
padding:0;
border:0;
outline:0;
font-size:100%;
vertical-align:baseline;
background:transparent;
}

article, aside, figure, footer, header,
hgroup, nav, section { display:block; }

nav ul { list-style:none; }

blockquote, q { quotes:none; }

blockquote:before, blockquote:after,
q:before, q:after { content:''; content:none; }

a { margin:0; padding:0; font-size:100%; vertical-align:baseline; background:transparent; }

ins { background-color:#ff9; color:#000; text-decoration:none; }

mark { background-color:#ff9; color:#000; font-style:italic; font-weight:bold; }

del { text-decoration: line-through; }

abbr[title], dfn[title] { border-bottom:1px dotted #000; cursor:help; }

/* tables still need cellspacing="0" in the markup */
table { border-collapse:collapse; border-spacing:0; }

hr { display:block; height:1px; border:0; border-top:1px solid #ccc; margin:1em 0; padding:0; }

input, select { vertical-align:middle; }
/* END RESET CSS */

 统一字体大小

为避免使用像素做字号单位在不同浏览器和操作系统之间解析不一致,下面的代码的片段将使网站字号跨平台始终保持一致。使用百分比设置字号请查看此文
/*
fonts.css from the YUI Library: developer.yahoo.com/yui/
Please refer to developer.yahoo.com/yui/fonts/ for font sizing percentages
*/
body { font:13px sans-serif; *font-size:small; *font:x-small; line-height:1.22; }
table { font-size:inherit; font:100%; }
select, input, textarea { font:99% sans-serif; }

 Webkit字体平滑

webkit浏览器字体反锯齿,可惜的是仅在Mac OSX中有效。主要使字体渲染得更加平滑、更易读,使字体没有细小的毛边,更多详情查看-webkit-font-smoothing
/* maxvoltar.com/archive/-webkit-font-smoothing */
html { -webkit-font-smoothing: antialiased; }

强制滚动条

有的时候,页面的高度小于浏览器的可视区域,浏览器(Firefox、Opera、Webkit)会自动隐藏滚动条。以下代码将强制浏览器无论页面多高都显示滚动条:
html { overflow-y: scroll; }

排版引用的代码

下面的代码片段使文本超出容器宽度时自动换行。使用它使pre标签同时跨浏览器保留换行和空格, 更多详情查看Formatting quoted code in blog posts: CSS2.1 white-space: pre-wrap
pre {
padding: 15px;
white-space: pre; /* CSS2 */
white-space: pre-wrap; /* CSS 2.1 */
white-space: pre-line; /* CSS 3 (and 2.1 as well, actually) */
word-wrap: break-word; /* IE */
}

对齐标签

在旧浏览器中实现标签和其相关input对齐是一个极其讨厌的工作,下面的代码解决该问题,使其跨浏览器保持一致。
/* align checkboxes, radios, text inputs with their label */
input[type="radio"] { vertical-align: text-bottom; }
input[type="checkbox"] { vertical-align: bottom; *vertical-align: baseline; }
.ie6 input { vertical-align: text-bottom; }

输入框可点击

出于某种原因,许多浏览器没有对一些可点击的input元素应用指针(手形)鼠标,下面的代码解决这个问题。
/* hand cursor on clickable input elements */
label, input[type=button], input[type=submit], button { cursor: pointer; }

屏幕阅读器访问

下面的代码片段使屏幕阅读器用户和鼠标用户访问链接时具有最佳可用性,达到两全其美。更多详情查看 Better CSS outline suppression
a:hover, a:active { outline: none; }
a, a:active, a:visited { color:#607890; }
a:hover { color:#036; }

IE7图片缩放

IE7默认的图片缩放算法是等比例缩小图片,效果很不好。为解决这个问题,只需开启IE7中可用的更好的缩放算法,处理效果果将达到所期望的像许多图片编辑软件一样。针对IE6的类似的解决方案请查看Flickr开发者写的On UI Quality (The Little Things): Client-side Image Resizing
/* bicubic resizing for non-native sized IMG:
code.flickr.com/blog/2008/11/12/on-ui-quality-the-little-things-client-side-image-resizing/ */
.ie7 img { -ms-interpolation-mode: bicubic; }

打印样式

任何得体的网站都应该有打印优化版本。尽管我们生活在一个信息技术驱动的时代,但是人们任然喜欢保存一些信息的实体拷贝。下面的代码片段首先使用CSS媒体声明,允许你将打印样式包含在主样式表中,而没有必要在网页头部放置另外一个链接。这样有利于减少载入时间,因为即使页面立刻被打印,浏览器也总是下载额外的CSS文件,产生额外的HTTP请求。下面的代码片段包含着一些有用的打印样式,例如打印链接url等。
/*
* print styles
* inlined to avoid required HTTP connection www.phpied.com/delay-loading-your-print-css/
*/
@media print {
* { background: transparent !important; color: #444 !important; text-shadow: none; }
  a, a:visited { color: #444 !important; text-decoration: underline; }
  a:after { content: " (" attr(href) ")"; }
  abbr:after { content: " (" attr(title) ")"; }&nbsp;&nbsp;&nbsp;&nbsp;.ir a:after { content: ""; } &nbsp;/* Don't show links for images */&nbsp;&nbsp;&nbsp;&nbsp;pre, blockquote { border: 1px solid #999; page-break-inside: avoid; }&nbsp;&nbsp;&nbsp;&nbsp;img { page-break-inside: avoid; }
  @page { margin: 0.5cm; }
  p, h2, h3 { orphans: 3; widows: 3; }
  h2, h3{ page-break-after: avoid; }
}

 设备适应

下面仅仅是两种网站开发可能用的两种css media queries,为智能手机和平板电脑的横屏和竖屏模式定义不同的样式 。
@media all and (orientation:portrait) {
/* Style adjustments for portrait mode goes here */
}

@media all and (orientation:landscape) {
/* Style adjustments for landscape mode goes here */
}

 .htaccess

html5 boilerplate和其他初始模板并不包含服务器端文件。下面是一些用于增强网站的.htaccess代码片段。

服务器端X-UA-Compatible

和上面提到的html版本类似,强制IE使用最新的渲染引擎,如果存在Chrome Frame则使用其渲染。放在.htaccess文件中的好处是不用再每个html文件的头部的添加代码,节省空间和宽带。
# Force IE to render pages in the highest available mode in the various
# cases when it may not: http://hsivonen.iki.fi/doctype/ie-mode.pdf.
# Use, if installed, Google Chrome Frame.

<IfModule mod_headers.c>
Header set X-UA-Compatible "IE=edge,chrome=1"
# mod_headers can't match based on the content-type, however, we only
# want to send this header for HTML pages and not for the other resources
<FilesMatch ".(appcache|crx|css|eot|gif|htc|ico|jpe?g|js|m4a|m4v|manifest|mp4|oex|oga|ogg|ogv|otf|pdf|png|safariextz|svg|svgz|ttf|vcf|webapp|webm|webp|woff|xml|xpi)$">
Header unset X-UA-Compatible
</FilesMatch>
</IfModule>

Gzip压缩

Gzip压缩能大大减小文件大小,提高加载速度。
<IfModule mod_deflate.c>
# Force compression for mangled headers.
# http://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping
&lt;IfModule mod_setenvif.c&gt;
    &lt;IfModule mod_headers.c&gt;
        SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
        RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    &lt;/IfModule&gt;
&lt;/IfModule&gt;

# Compress all output labeled with one of the following MIME-types
# (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
#  and can remove the `&lt;IfModule mod_filter.c&gt;` and `&lt;/IfModule&gt;` lines
#  as `AddOutputFilterByType` is still in the core directives).
&lt;IfModule mod_filter.c&gt;
    AddOutputFilterByType DEFLATE application/atom+xml \
                                  application/javascript \
                                  application/json \
                                  application/rss+xml \
                                  application/vnd.ms-fontobject \
                                  application/x-font-ttf \
                                  application/x-web-app-manifest+json \
                                  application/xhtml+xml \
                                  application/xml \
                                  font/opentype \
                                  image/svg+xml \
                                  image/x-icon \
                                  text/css \
                                  text/html \
                                  text/plain \
                                  text/x-component \
                                  text/xml
&lt;/IfModule&gt;

</IfModule>

缓存文件有效期

为提高访问速度我们通常在用户的机器上缓存文件,需根据网站更新的频繁程度设置缓存期限。
# ------------------------------------------------------------------------------
# | ETag removal                                                               |
# ------------------------------------------------------------------------------

Since we're sending far-future expires headers (see below), ETags can

be removed: http://developer.yahoo.com/performance/rules.html#etags.

FileETag None is not enough for every server.

<IfModule mod_headers.c>
Header unset ETag
</IfModule>

FileETag None

------------------------------------------------------------------------------

| Expires headers (for better cache control) |

------------------------------------------------------------------------------

The following expires headers are set pretty far in the future. If you don't

control versioning with filename-based cache busting, consider lowering the

cache time for resources like CSS and JS to something like 1 week.

<IfModule mod_expires.c>

ExpiresActive on
ExpiresDefault                                      "access plus 1 month"

CSS

ExpiresByType text/css                              "access plus 1 year"

Data interchange

ExpiresByType application/json                      "access plus 0 seconds"
ExpiresByType application/xml                       "access plus 0 seconds"
ExpiresByType text/xml                              "access plus 0 seconds"

Favicon (cannot be renamed!)

ExpiresByType image/x-icon                          "access plus 1 week"

HTML components (HTCs)

ExpiresByType text/x-component                      "access plus 1 month"

HTML

ExpiresByType text/html                             "access plus 0 seconds"

JavaScript

ExpiresByType application/javascript                "access plus 1 year"

Manifest files

ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
ExpiresByType text/cache-manifest                   "access plus 0 seconds"

Media

ExpiresByType audio/ogg                             "access plus 1 month"
ExpiresByType image/gif                             "access plus 1 month"
ExpiresByType image/jpeg                            "access plus 1 month"
ExpiresByType image/png                             "access plus 1 month"
ExpiresByType video/mp4                             "access plus 1 month"
ExpiresByType video/ogg                             "access plus 1 month"
ExpiresByType video/webm                            "access plus 1 month"

Web feeds

ExpiresByType application/atom+xml                  "access plus 1 hour"
ExpiresByType application/rss+xml                   "access plus 1 hour"

Web fonts

ExpiresByType application/font-woff                 "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
ExpiresByType application/x-font-ttf                "access plus 1 month"
ExpiresByType font/opentype                         "access plus 1 month"
ExpiresByType image/svg+xml                         "access plus 1 month"

</IfModule>

进一步思考

强烈建议再回去查看 Html5 Boilerplate,这个不可思议的资源涵盖的不仅仅是这些代码片段,我相信你会有更多的收获。

via 20 Snippets You should be using from Html5 Boilerplate