URI 以两个斜杠开始... 它们的行为如何?

最近我看到 工作代码块是这样的:

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

根据 RFC 2396(URI 语法)和 RFC 2616(HTTP 1.1) ,这些以两个斜杠开头的 URI 是有效的,但不幸的是 RFC 并没有真正解释它们。

有没有人能告诉我浏览器是如何处理这些 URI 的?

22501 次浏览

They are protocol independent urls. If the web page is served on https then the request uses https, if http then http.

Paul Irish seems to have popularized them by including it in his boilerplate code.

These are protocol relative URLs. They point to an address, keeping the current protocol.

This notation is often used to avoid the "mixed content" problem (a IE warning message complaining about http and https resources on the same HTTPS page).

Update: Official documentation in RFC 3986:

A relative reference that begins with two slash characters is termed a network-path reference; such references are rarely used. A relative reference that begins with a single slash character is termed an absolute-path reference. A relative reference that does not begin with a slash character is termed a relative-path reference.

The resource you're looking for is the RFC 3986.

See Section 4.2 and Section 5.4. Quoting from the latter:

Reference Resolution Examples

Within a representation with a well defined base URI of:

    http://a/b/c/d;p?q

a relative reference is transformed to its target URI as follows:

  "g:h"           =  "g:h"
"g"             =  "http://a/b/c/g"
"./g"           =  "http://a/b/c/g"
"g/"            =  "http://a/b/c/g/"
"/g"            =  "http://a/g"
"//g"           =  "http://g"
"?y"            =  "http://a/b/c/d;p?y"
"g?y"           =  "http://a/b/c/g?y"
"#s"            =  "http://a/b/c/d;p?q#s"
"g#s"           =  "http://a/b/c/g#s"
"g?y#s"         =  "http://a/b/c/g?y#s"
";x"            =  "http://a/b/c/;x"
"g;x"           =  "http://a/b/c/g;x"
"g;x?y#s"       =  "http://a/b/c/g;x?y#s"
""              =  "http://a/b/c/d;p?q"
"."             =  "http://a/b/c/"
"./"            =  "http://a/b/c/"
".."            =  "http://a/b/"
"../"           =  "http://a/b/"
"../g"          =  "http://a/b/g"
"../.."         =  "http://a/"
"../../"        =  "http://a/"
"../../g"       =  "http://a/g"

This means that when the base URI is http://a/b/c/d;p?q and you use //g, the relative reference is transformed to http://g.

Be aware of that it is not only http or https independent, but also file, ftp, etc.

It means if you open .htm file directly in your browser on localhost, browser will resolve // as file protocol and your page won't work. It may cause problems in packed websites as "native" app using tools like Electron, PhoneGap, etc.

Example:

<script src="//mywebsite.com/resource.js"></script>

to

<script src="file://mywebsite.com/resource.js"></script>