戴夫·沃德说,

It’s not exactly light reading, but section 4.2 of RFC 3986 provides for fully qualified URLs that omit protocol (the HTTP or HTTPS) altogether. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead. Put simply, these “protocol-less” URLs allow a reference like this to work in every browser you’ll try it in: //ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js It looks strange at first, but this “protocol-less” URL is the best way to reference third party content that’s available via both HTTP and HTTPS.

这当然可以解决我们在HTTP页面上看到的一堆混合内容错误——假设我们的资产可以通过HTTP和HTTPS使用。

这是完全跨浏览器兼容的吗?还有其他注意事项吗?


当前回答

如果你想确保所有的请求都升级到安全协议,那么有一个简单的选项,使用内容安全策略标头升级-不安全-请求

Content-Security-Policy: upgrade-insecure-requests;

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

其他回答

考虑到是否应该这样做,是否可以将其所有链接更改为协议相关的问题可能是没有意义的。Paul Irish说:

2014.12.17:既然SSL是鼓励每个人使用的,并且没有性能问题,那么这个技术现在是一个反模式。如果 你需要的资产在SSL上是可用的,那么总是使用https:// 资产。

是的,网络路径引用已经在RFC 1808中指定,并且应该适用于所有浏览器。

在发布前我进行了彻底的测试。在所有可以在Browsershots上测试的浏览器中,我只能找到一个不能正确处理协议相对URL的浏览器:一个名为Dillo的*nix浏览器。

我收到的反馈有两个缺点:

Protocol-less URLs may not work as expected when you "open" a local file in your browser, because the page's base protocol will be file:///. Especially when you're using the protocol-less URL for an external resource like a CDN-hosted asset. Using a local web server like Apache or IIS to test against http://localhost addresses works fine though. Apparently there's at least one iPhone feed reader app that does not handle the protocol-less URLs correctly. I'm not aware of which one has the problem or how popular it is. For hosting a JavaScript file, that's not a big problem since RSS readers typically ignore JavaScript content anyway. However, it could be an issue if you're using these URLs for media like images inside content that needs to be syndicated via RSS (though, this single reader app on a single platform probably accounts for a very marginal number of readers).

我在使用://example.com时没有遇到这些问题-但您确实需要在开头添加冒号。你之前写过一篇关于这方面的文章。但却被他的一堆博客帖子淹没了。

这是完全跨浏览器兼容的吗?还有其他注意事项吗?

如果您是在本地服务器上开发,那么它可能无法工作。您需要指定一个方案,否则浏览器可能会假设src="//cdn.example.com/js_file.js"是src="file://cdn.example.com/js_file.js",这将破坏,因为您没有在本地托管这个资源。

微软ie浏览器似乎对这一点特别敏感,看这个问题:无法在本地主机上加载jQuery (WAMP)

您可能总是试图找到一种解决方案,该解决方案适用于所有环境,所需的修改最少。

HTML5Boilerplate使用的解决方案是在资源没有正确加载时有一个回退,但只有当你合并一个检查时才有效:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- If jQuery is not defined, something went wrong and we'll load the local file -->
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>

我把这个答案也贴在这里了。

更新:HTML5Boilerplate现在使用<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">后决定弃用协议相对url,见这里。