我有以下元素:

<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:?

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


当前回答

当使用//somedomain.com作为JS文件的引用时,我们在日志中看到404错误。

导致404的引用是这样的: 裁判:

<script src="//somedomain.com/somescript.js" />

404请求:

http://mydomain.com//somedomain.com/somescript.js

由于这些问题经常出现在我们的web服务器日志中,可以肯定地说:所有浏览器和机器人都不遵守RFC 3986第4.2节。最安全的做法是尽可能地包含协议。

其他回答

许多人称之为协议相对URL。

它会导致IE 7和IE 8中CSS文件的双重下载。

由于您的示例链接到外部域,如果您使用的是HTTPS,那么您应该验证外部域也为SSL设置了。否则,您的用户可能会看到SSL错误和/或404错误(例如,旧版本的Plesk将HTTP和HTTPS存储在单独的文件夹中)。对于cdn,这应该不是一个问题,但对于任何其他网站,这可能是一个问题。

另一方面,在更新旧网站时进行测试,也可以在META REFRESH的url=部分中工作。

在这里,我在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.

我在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,文件。

不使用协议是完全合理的。URL规范多年来一直对此非常明确,我还没有发现一个浏览器不理解这一点。我不知道为什么这个技巧不为人所知;它是跨越HTTP/HTTPS边界这一棘手问题的完美解决方案。更多信息:Http-https转换和相对url