的初步认识

2017-03-14  本文已影响0人  饥人谷_Bayes

Coursera 学习 HTML CSS JavaScript for Web Developers 的时候,有讲如果要让网页在移动设备上更好的显示,需要在 HTML 中的 <head> 里加上这一行代码:

<meta name="viewport" content="width=device-width, initial-scale=1">

使用 Hexo 在搭建博客时也发现了类似的内容:

<meta name="generator" content="Bayestheorem">
<meta name="author" content="Bayes Zou">
<meta name="description" content="BayesZ">
<meta name="keywords" content="">

当时并没有太在意 <meta> 的作用,认为不过是一些「约定好的声明」罢了。然后听方老师的课知道了 Github 上的这个项目[1],感觉这才第一次认识了这个元素。

是什么

借用 MDN 的描述:

The HTML <meta> element represents any metadata information that cannot be represented by one of the other HTML meta-related elements. (<base>, <link>, <script>, <style> or <title>).

<meta> 元素表示所有不能被其他 HTML 元相关元素(如 <base>, <link>, <script>, <style> or <title>)表示的元信息。

<meta> 里的信息不会显示在页面上,因为这不是给用户看的,而是提供给机器的信息。

<meta> 不该写成 <meta/>

<meta> 元素有两个属性(attribute),http-equivname 属性,以及和属性对应的属性值(content)。有兴趣了解详细信息的可以自行查阅[2],这里主要想总结下自己所理解的 <meta> 元素能做什么,和一点相关思考。

能做的

关于浏览器

<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="renderer" content="webkit|ie-comp|ie-stand">
<meta name="apple-mobile-web-app-capable" content="yes"> 
<meta http-equiv="Expires" content="0">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Cache-Control" content="no-cache">

还有许多作用,例如开头提及的优化移动端的显示,站点适配等等。

SEO 优化

<meta name="description" content="your words">
<meta name="keyword" content="your tags">
<meta http-equiv="refresh" content="0;url=">

除了以上,和可以声明网页作者,设置搜索引擎索引方式,标注版权信息等等。

相关思考

<meta> 的位置

在查阅关于 <meta> 信息的过程中看到这样一个回答:

...叫头标签,需要写在 meta 内部最前面,在它之前你唯一能写的只有 "title", 其他都不可以。

关于 <meta><head> 中的位置,规范中似乎没有找到要求。经搜索发现贺老在知乎的答案[3]

没有特定规定。
不过我至少有一条建议:确保 <meta charset=encoding> 放在最前,让浏览器尽早获得字符编码信息,如果要浏览器据此决定转码可以早点转。

越来越长的 <head>

看到 HEAD[1] 的时候,本能有两个反应:

天啊,靠 <head> 原来能做这么多事?!😳

以及

天啊,原来这么多平台都各自靠 <head> 做这么多事?!☹️

有些 <meta> & <link> 定义重复,但是为了兼容不同私有平台的「私货」,使 <head> 被越塞越满,尤其一些 Web App:

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="images/touch/apple-touch-icon-144x144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="images/touch/apple-touch-icon-114x114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="images/touch/apple-touch-icon-72x72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="images/touch/apple-touch-icon-57x57-precomposed.png">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="Lighten">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<mate name="theme-color" content="#000000">

W3C WebApps 工作组指定的 W3C Web App Manifest 不失为一种好的解决办法。或许在将来,不停加 <meta>/<link> 的做法会被使用 JSON 代替。

其他参考


  1. GitHub HEAD

  2. HTML 标准规范MDN 及 Lxxyx 的文章

  3. 前端规范,HTML 的 <head> 标签内 <meta><title> 等标签顺序是怎样的?

上一篇 下一篇

猜你喜欢

热点阅读