前言
最近基于 https 的网站,引用 http 网站的资源文件出现了报错,最初的解决办法是添加两套引入,也就是 http
、 https
都写上
<script src="http://a.js"></script>
<script src="https://a.js"></script>
可是最近发现一个有趣的事情,读他人的代码发现,去掉 URL 中的协议部分,浏览器就可以自动识别并引入资源:
<script src="//a.js"></script>
我查了下,这个叫 The Protocol-relative URL,在浏览器的一种路径写法:
<!-- 绝对路径 -->
<script src="/a.js"></script>
<!-- 相对路径 -->
<script src="a.js"></script>
<!-- 协议绝对网址 -->
<script src="http://a.js"></script>
<script src="https://a.js"></script>
<!-- 协议相对网址 -->
<script src="//a.js"></script>
Technically, this is called a “network-path reference” according to RFC 3986.
Oh and if you want to be truly correct, you’ll use the term “scheme” instead of “protocol” when talking about URLs.
缺点
仅仅是老版本的IE浏览器有点问题,现今的浏览器都是可以自动处理的
- IE7和IE8 会重复下载两次:When used on a or @import for a stylesheet, IE7 and IE8 download the file twice. All other uses, however, are just fine.
- 在IE6中不生效:The reason this doesn’t work in IE6 is that the server is using SNI to deduce what certificate to return. XP (and thus IE6) doesn’t support SNI in the HTTPS stack. See for details.
相关链接
The Protocol-relative URL
Network-Path Reference URI / Scheme relative URLs