问题描述
在页面中使用 JavaScript 有两种常用的方式:
-
直接写在
script标签内<script> const app = {} </script> -
通过
script标签 src 属性引入外部的 JS 文件<script src="/js/app.js"></script>
类似的,在使用 CSS 的时候,我们也可以:
- 直接写的
style标签内<style> body { color: red } </style> - 通过
style标签的 src 属性引入 CSS 外部文件<style src="/css/style.css"></style>
等等,好像有哪里不对?
外部 CSS 的引入方式应该是:
<link rel="stylesheet" href="/css/style.css" />
这是为什么呢?
为什么在引入 CSS 的时候不使用 <style src=""></style>,而要使用 <link rel="stylesheet" href=" /> 呢?
一句话结论
在需要引入样式表的时候,style 和 script 标签的标准还没有制定出来(没得用)[1],于是选用了现成的 link 标签来做样式表的引入。
考古过程
根据 W3C 的文档,我们可以梳理出这样一条时间线。
- 1995/09/22 - HTML 2.0 标准发布[2],提到使用
link标签来引入样式表,此时标准中还未出现style标签。The LINK element is typically used to indicate authorship, related indexes and glossaries, older or more recent versions, document hierarchy, associated resources such as style sheets, etc.
- 1996/12/17 - CSS 1 标准发布[3],提到四种 CSS 的引入方式,除了
link的引入方式之外,增加了style标签、@import、内联样式。The example shows four ways to combine style and HTML: using the 'LINK' element to link an external style sheet, a 'STYLE' element inside the 'HEAD' element, an imported style sheet using the CSS '@import' notation, and a 'STYLE' attribute on an element inside 'BODY'.
- 1997/01/14 - HTML 3.2 标准发布[4],标准中正式出现
style和script,此时这两个标签只是占位,并未制定出详细的标准。These are place holders for the introduction of style sheets and client-side scripts in future versions of HTML. User agents should hide the contents of these elements.
- 1997/12/18 - HTML 4.0 规范发布[5],详细给出
style和script的标准。至此相关标准基本制定完成。
彩蛋
有趣的是,在上文提到的 HTML 3.2 的标准中,关于 link 标签的功能提到了这样一句话[6]:
for linking associated resources such as style sheets and scripts
用于链接相关资源,例如样式表和脚本
也就是说在 HTML 3.2 的时候考虑过使用 link 标签来引入 JavaScript 脚本。
如果后来没有修改的话,现在引入 JavaScript 方式可能就是 <link ref="script" href="/js/app.js" />了。
那么为什么最终没有选择 <link />,而选择了<script src=""></script> 呢?
对此,你有什么看法呢?