我有以下元素:

<script type="text/javascript" src="https://cdn.example.com/js_file.js"></script>

在这种情况下,站点是HTTPS,但站点也可能只是HTTP。(JS文件在另一个域中。)为了方便起见,我想知道是否可以这样做:

<script type="text/javascript" src="//cdn.example.com/js_file.js"></script>

我想知道是否可以删除http:或https:?

它似乎在我测试过的所有地方都有效,但是否有任何情况下它不起作用?


当前回答

我在html5-boilerplate上看到的模式是:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

它可以在不同的方案上顺利运行,如http, https,文件。

其他回答

是的,这在RFC 3986章节5.2中有记录:

(编辑:哎呀,我的RFC引用过时了)。

有没有什么情况下它不起作用?

如果父页面是从file://加载的,那么它可能无法工作(它将尝试获取file://cdn.example.com/js_file.js,当然您也可以在本地提供)。

我在html5-boilerplate上看到的模式是:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

它可以在不同的方案上顺利运行,如http, https,文件。

在这里,我在HTML的隐藏特性中复制了答案:

Using a protocol-independent absolute path: <img src="//domain.com/img/logo.png"/> If the browser is viewing an page in SSL through HTTPS, then it'll request that asset with the https protocol, otherwise it'll request it with HTTP. This prevents that awful "This Page Contains Both Secure and Non-Secure Items" error message in IE, keeping all your asset requests within the same protocol. Caveat: When used on a <link> or @import for a stylesheet, IE7 and IE8 download the file twice. All other uses, however, are just fine.

没有方案的相对URL (http:或https:)是有效的,根据RFC 3986:“统一资源标识符(URI):通用语法”,章节4.2。如果客户端阻塞了它,那么这是客户端的错,因为它们没有遵守RFC中指定的URI语法。

你的例子是有效的,应该可以工作。我自己在访问量很大的网站上使用过相对URL方法,没有人抱怨。此外,我们还在Firefox、Safari、IE6、IE7和Opera上测试我们的网站。这些浏览器都能理解URL格式。