不温不火的AMP

AMP全称是Accelerated Mobile Pages,由谷歌提出,目的是通过改造一部分html的样式来给移动端网页加速。不过这个式样自从提出来之后除了少许有博文介绍,一直是不温不火,导致我有几次看到都毫无兴趣地略过了。

我们可以从这里了解快速生成一个AMP页面的方法。

如何把网页AMP化?

其实总而言之,从一般的网页到AMP支持的网页只需要几点。

必须的markup形式

  • html 文件以 <!doctype html>开头。

  • html的top的dom元素需要为<html ⚡> tag (或者是<html amp>)

  • 需要有<head><body> tag。(在传统html中它们不是必须的)

  • 包含一个 <link rel="canonical" href="$SOME_URL" /> tag 指向没有导入AMP的原版网页,如果我们仅有AMP网页,那么使用相同的url就行了。

  • 需要把 <meta charset="utf-8"> 作为<head> tag的第一个子元素。

  • 需要包含一个<meta name="viewport" content="width=device-width,minimum-scale=1">的tag,同时推荐其属性包含initial-scale=1

  • <head> tag里面需要包含一个 <script async src="https://cdn.ampproject.org/v0.js"></script> 的tag。

  • 需要在<head>tag中包含<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    tag。

把AMP化之后和非AMP相应的页面捆绑起来

发布的时候需要,在非AMP的页面中使用<link rel="amphtml" href="https://www.example.com/url/to/amp/document.html">,而在AMP页面中使用<link rel="amphtml" href="https://www.example.com/url/to/amp/document.html"> 来把这个内容相同,但是只不过是对应AMP与否区别的两个页面捆绑起来。

其它注意点

一些tag需要使用AMP专用的形式。比如img tag需要改成 amp-img, 类似的还有video,audio,iframe等等。

另外一些event,class,id的名称也要注意。基本就是注意有些形式不能用。 比如其中带-amp-的id。比较重要的有一点,就是css只能用on page的 style tag来指定。

这些规则比较杂乱也不是本文重点,我们可以参考这里

Hexo中引入AMP。

其实写一个支持AMP的模版是最传统的做法。当然,我们还可以使用这个插件
其实我们发现,这个插件做的事情无非也就是另起炉灶搞一个模版,然后用这个模版渲染新的AMP的页面,然后把新老页面通过上面的link tag捆绑起来而已。

后话

AMP这个概念其实自从提出来一直不温不火,从官网的doc的中文翻译只翻译了标题就可以看出来。另外谷歌已经明确说过AMP对SEO并没有直接效果。至于是否有必要去趟水导入,那就请自己判断了。