我有以下元素:

<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: 是否有效: ?

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

I have the following element:

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

In this case the site is HTTPS, but the site may also be just HTTP. (The JS file is on another domain.) I'm wondering if it's valid to do the following for convenience sake:

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

I'm wondering if it's valid to remove the http: or https:?

It seems to work everywhere I have tested, but are there any cases where it doesn't work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

毁虫ゝ 2024-09-11 10:19:47

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

你的例子是有效的并且应该有效。我自己在流量大的网站上使用过相对 URL 方法,并且投诉为零。此外,我们还在 Firefox、Safari、IE6、IE7 和 Opera 中测试了我们的网站。这些浏览器都可以理解该 URL 格式。

A relative URL without a scheme (http: or https:) is valid, per RFC 3986: "Uniform Resource Identifier (URI): Generic Syntax", Section 4.2. If a client chokes on it, then it's the client's fault because they're not complying with the URI syntax specified in the RFC.

Your example is valid and should work. I've used that relative URL method myself on heavily trafficked sites and have had zero complaints. Also, we test our sites in Firefox, Safari, IE6, IE7 and Opera. These browsers all understand that URL format.

⒈起吃苦の倖褔 2024-09-11 10:19:47

它保证可以在任何主流浏览器中运行(我不考虑市场份额低于 0.05% 的浏览器)。哎呀,它可以在 Internet Explorer 3.0 中运行。

RFC 3986 定义 URI 由以下部分组成:

     foo://example.com:8042/over/there?name=ferret#nose
     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment

定义时相对 URI(第 5.2 节),您可以省略任何这些部分,总是从左边开始。在伪代码中,它看起来像这样:

 result = ""

  if defined(scheme) then
     append scheme to result;
     append ":" to result;
  endif;

  if defined(authority) then
     append "//" to result;
     append authority to result;
  endif;

  append path to result;

  if defined(query) then
     append "?" to result;
     append query to result;
  endif;

  if defined(fragment) then
     append "#" to result;
     append fragment to result;
  endif;

  return result;

您所描述的 URI 是一个无方案的相对 URI。

It is guaranteed to work in any mainstream browser (I'm not taking browsers with less than 0.05% market share into consideration). Heck, it works in Internet Explorer 3.0.

RFC 3986 defines a URI as composed of the following parts:

     foo://example.com:8042/over/there?name=ferret#nose
     \_/   \______________/\_________/ \_________/ \__/
      |           |            |            |        |
   scheme     authority       path        query   fragment

When defining relative URIs (Section 5.2), you can omit any of those sections, always starting from the left. In pseudo-code, it looks like this:

 result = ""

  if defined(scheme) then
     append scheme to result;
     append ":" to result;
  endif;

  if defined(authority) then
     append "//" to result;
     append authority to result;
  endif;

  append path to result;

  if defined(query) then
     append "?" to result;
     append query to result;
  endif;

  if defined(fragment) then
     append "#" to result;
     append fragment to result;
  endif;

  return result;

The URI you are describing is a scheme-less relative URI.

情场扛把子 2024-09-11 10:19:47

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

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

are there any cases where it doesn't work?

If the parent page was loaded from file://, then it probably does not work (it will try to get file://cdn.example.com/js_file.js, which of course you could provide locally as well).

怎言笑 2024-09-11 10:19:47

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

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

Many people call this a Protocol Relative URL.

It causes a double-download of CSS files in IE 7 & 8.

尘曦 2024-09-11 10:19:47

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

使用独立于协议的绝对
路径:


如果浏览器正在查看以下页面
SSL 通过 HTTPS,然后它会请求
该资产采用 https 协议,
否则它将使用 HTTP 请求。

这可以防止可怕的“此页面
包含安全和非安全
Items” IE 中的错误消息,保留
您的所有资产请求
相同的协议。

警告:当用于
@import 用于样式表、IE7 和 IE8
下载文件两次。所有其他
不过,用途还不错。

Here I duplicate the answer in Hidden features of 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.

╰◇生如夏花灿烂 2024-09-11 10:19:47

放弃协议是完全有效的。多年来,URL 规范对此已经非常明确,而且我还没有找到不理解它的浏览器。我不知道为什么这种技术没有被更多人所知;它是跨 HTTP/HTTPS 边界这一棘手问题的完美解决方案。更多信息请参见:Http-https 转换和相对 URL

It is perfectly valid to leave off the protocol. The URL spec has been very clear about this for years, and I've yet to find a browser that doesn't understand it. I don't know why this technique isn't better known; it's the perfect solution to the thorny problem of crossing HTTP/HTTPS boundaries. More here: Http-https transitions and relative URLs

橘寄 2024-09-11 10:19:47

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

只是将其混合在一起,如果您在本地服务器上进行开发,它可能无法工作。您需要指定一个方案,否则浏览器可能会认为 src="//cdn.example.com/js_file.js"src="file://cdn.example. com/js_file.js",由于您没有在本地托管此资源,因此该文件将会中断。

Microsoft Internet Explorer 似乎对此特别敏感,请参阅此问题:无法在本地主机上的 Internet Explorer (WAMP) 中加载 jQuery

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

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 现在使用

are there any cases where it doesn't work?

Just to throw this in the mix, if you are developing on a local server, it might not work. You need to specify a scheme, otherwise the browser may assume that src="//cdn.example.com/js_file.js" is src="file://cdn.example.com/js_file.js", which will break since you're not hosting this resource locally.

Microsoft Internet Explorer seem to be particularly sensitive to this, see this question: Not able to load jQuery in Internet Explorer on localhost (WAMP)

You would probably always try to find a solution that works on all your environments with the least amount of modifications needed.

The solution used by HTML5Boilerplate is to have a fallback when the resource is not loaded correctly, but that only works if you incorporate a check:

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

UPDATE: HTML5Boilerplate now uses <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js after deciding to deprecate protocol relative URLs, see [here][3].

甜是你 2024-09-11 10:19:47

1.

2019 年总结答案:您仍然可以使用协议相对 URL,但是这种技术 反模式

另外:

  1. 你可能在开发中遇到问题。
  2. 某些第三方工具可能不支持它们。

从协议相关 URL 迁移到 https:// 会很好。


2. 相关性

该答案与 2019 年 1 月相关。将来,该答案的数据可能会过时。


3. 反模式

3.1。论证

Paul Irish — Google Chrome 的前端工程师和开发者倡导者写于 2014 年 12 月

现在 SSL 鼓励所有人使用并且没有性能问题此技术现在是一种反模式。如果您需要的资产可通过 SSL 获取,则始终使用 https:// 资产。

允许通过 HTTP 请求代码段为 最近的 GitHub 人机攻击。即使您的网站使用 HTTP,请求 HTTPS 资源始终是安全的,但反之亦然 不正确

3.2.另一个链接

3.3.示例


4. 开发流程

例如,我尝试使用 clean-console

  • 示例文件 KiraCleanConsole__cdn_links_demo.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>clean-console without protocol demonstration</title>
    <!-- Really dead link -->
    <script src="https://unpkg.com/bowser@latest/bowser.min.js"></script>
    <!-- Package exists; link without “https:” -->
    <script src="//cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    <!-- Package exists: link with “https:” -->
    <script src="https://cdn.jsdelivr.net/npm/gemini-scrollbar/index.js"></script>
</head>
<body>
    Kira Goddess!
</body>
</html>
  • 输出:
D:\SashaDebugging>clean-console -i KiraCleanConsole__cdn_links_demo.html
checking KiraCleanConsole__cdn_links_demo.html
phantomjs: opening page KiraCleanConsole__cdn_links_demo.html

phantomjs: Unable to load resource (#3URL:file://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js)


phantomjs:   phantomjs://code/runner.js:30 in onResourceError
Error code: 203. Description: Error opening //cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js: The network path was not found.

  phantomjs://code/runner.js:31 in onResourceError

phantomjs: Unable to load resource (#5URL:https://unpkg.com/[email protected]/bowser.min.js)


phantomjs:   phantomjs://code/runner.js:30 in onResourceError
Error code: 203. Description: Error downloading https://unpkg.com/[email protected]/bowser.min.js - server replied: Not Found

  phantomjs://code/runner.js:31 in onResourceError

phantomjs: Checking errors after sleeping for 1000ms
2 error(s) on KiraCleanConsole__cdn_links_demo.html

phantomjs process exited with code 2

链接 //cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js 有效,但我收到错误。

关注file://cdn.jsdelivr.net/npm/[电子邮件] protected]/dist/jquery.min.js 并阅读 Thilobg17aw 关于 file:// 的回答。

我不知道这种行为,也不明白为什么我会遇到这样的问题 页面


5.第三方工具

我使用Clickable URLs Sublime Text包。使用它,我可以简单地从浏览器中的文本编辑器打开链接。

CSS links Examples

示例中的两个链接均有效。但我可以使用可点击 URL 在浏览器中成功打开第一个链接,第二个链接则不能。这可能不是很方便。


6. 结论

是:

  1. 如果您遇到开发流程项中的问题,您可以设置您的开发流程。
  2. 否则您遇到第三方工具项中的问题,您可以贡献工具。

但你不需要这些额外的问题。通过反模式项中的链接读取信息:协议相对 URL 已过时。

1. Summary

Answer for 2019: you can still use protocol-relative URLs, but this technique an anti-pattern.

Also:

  1. You may have problems in developing.
  2. Some third-party tools may not support them.

Migrating from protocol-relative URLs to https:// it would be nice.


2. Relevance

This answer is relevant for January 2019. In the future, the data of this answer may be obsolete.


3. Anti-pattern

3.1. Argumentation

Paul Irish — front-end engineer and a developer advocate for the Google Chromewrite in 2014, December:

Now that SSL is encouraged for everyone and doesn’t have performance concerns, this technique is now an anti-pattern. If the asset you need is available on SSL, then always use the https:// asset.

Allowing the snippet to request over HTTP opens the door for attacks like the recent GitHub Man-on-the-side attack. It’s always safe to request HTTPS assets even if your site is on HTTP, however the reverse is not true.

3.2. Another links

3.3. Examples


4. Developing process

For example, I try to use clean-console.

  • Example file KiraCleanConsole__cdn_links_demo.html:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>clean-console without protocol demonstration</title>
    <!-- Really dead link -->
    <script src="https://unpkg.com/bowser@latest/bowser.min.js"></script>
    <!-- Package exists; link without “https:” -->
    <script src="//cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
    <!-- Package exists: link with “https:” -->
    <script src="https://cdn.jsdelivr.net/npm/gemini-scrollbar/index.js"></script>
</head>
<body>
    Kira Goddess!
</body>
</html>
  • output:
D:\SashaDebugging>clean-console -i KiraCleanConsole__cdn_links_demo.html
checking KiraCleanConsole__cdn_links_demo.html
phantomjs: opening page KiraCleanConsole__cdn_links_demo.html

phantomjs: Unable to load resource (#3URL:file://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js)


phantomjs:   phantomjs://code/runner.js:30 in onResourceError
Error code: 203. Description: Error opening //cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js: The network path was not found.

  phantomjs://code/runner.js:31 in onResourceError

phantomjs: Unable to load resource (#5URL:https://unpkg.com/[email protected]/bowser.min.js)


phantomjs:   phantomjs://code/runner.js:30 in onResourceError
Error code: 203. Description: Error downloading https://unpkg.com/[email protected]/bowser.min.js - server replied: Not Found

  phantomjs://code/runner.js:31 in onResourceError

phantomjs: Checking errors after sleeping for 1000ms
2 error(s) on KiraCleanConsole__cdn_links_demo.html

phantomjs process exited with code 2

Link //cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js is valid, but I getting an error.

Pay attention to file://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js and read Thilo and bg17aw answers about file://.

I didn't know about this behavior and couldn't understand why I have problems like this for pageres.


5. Third-party tools

I use Clickable URLs Sublime Text package. Use it, I can simply open links from my text editor in browser.

CSS links examples

Both links in example are valid. But first link I can successfully open in browser use Clickable URLs, second link — no. This may not be very convenient.


6. Conclusion

Yes:

  1. If you have problems as in Developing process item, you can set your development workflow.
  2. Else you have problems as in Third-party tools item, you can contribute tools.

But you don't need this additional problems. Read information by links in Anti-pattern item: protocol-relative URLs is obsolete.

情愿 2024-09-11 10:19:47

根据 gnud 的参考,RFC 3986 第 5.2 节 说:

如果定义了scheme组件,说明引用
以方案名称开头,然后引用被解释为
绝对 URI,我们就完成了。 否则,引用 URI 的方案
继承自基本 URI 的方案组件

所以 // 是正确的:-)

Following the gnud's reference, the RFC 3986 section 5.2 says:

If the scheme component is defined, indicating that the reference
starts with a scheme name, then the reference is interpreted as an
absolute URI and we are done. Otherwise, the reference URI's scheme
is inherited from the base URI's scheme component
.

So // is correct :-)

赠佳期 2024-09-11 10:19:47

是的,这记录在 RFC 3986,第 5.2 节中:(

编辑:哎呀,我的RFC 参考已过时)。

Yes, this is documented in RFC 3986, section 5.2:

(edit: Oops, my RFC reference was outdated).

又怨 2024-09-11 10:19:47

正如其他答案所说,这确实是正确的。但您应该注意,某些网络爬虫会像本地 URL 一样在您的服务器上请求这些内容,从而引发 404 错误。 (他们忽略双斜杠并将其视为单斜杠)。

您可能需要在网络服务器上设置规则来捕获这些内容并重定向它们。

例如,对于 Nginx,您可以添加类似以下内容:

location ~* /(?<redirect_domain>((([a-z]|[0-9]|\-)+)\.)+([a-z])+)/(?<redirect_path>.*) {
  return 301 $scheme:/$redirect_domain/$redirect_path;
}

但请注意,如果您在 URI 中使用句点,则需要增加特异性,否则最终会将这些页面重定向到不存在的域。

此外,这是一个为每个查询运行的相当大的正则表达式——在我看来,用 404 来惩罚不兼容的浏览器是值得的,而不是对大多数兼容的浏览器造成(轻微的)性能影响。

It is indeed correct, as other answers have stated. You should note though, that some web crawlers will set off 404s for these by requesting them on your server as if a local URL. (They disregard the double slash and treat it as a single slash).

You may want to set up a rule on your webserver to catch these and redirect them.

For example, with Nginx, you'd add something like:

location ~* /(?<redirect_domain>((([a-z]|[0-9]|\-)+)\.)+([a-z])+)/(?<redirect_path>.*) {
  return 301 $scheme:/$redirect_domain/$redirect_path;
}

Do note though, that if you use periods in your URIs, you'll need to increase the specificity or it will end up redirecting those pages to nonexistent domains.

Also, this is a rather massive regex to be running for each query -- in my opinion, it's worth punishing non-compliant browsers with 404s over a (slight) performance hit on the majority of compliant browsers.

溺渁∝ 2024-09-11 10:19:47

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

导致 404 的引用看起来像这样:
ref:

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

404 请求:

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

随着这些定期出现在我们的网络服务器日志中,可以肯定地说:所有浏览器和机器人遵守 RFC 3986 第 4.2 节。最安全的选择是尽可能包含协议。

We are seeing 404 errors in our logs when using //somedomain.com as references to JS files.

The references that cause the 404s come out looking like this:
ref:

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

404 request:

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

With these showing up regularly in our web server logs, it is safe to say that: All browsers and Bots DO NOT honor RFC 3986 section 4.2. The safest bet is to include the protocol whenever possible.

静若繁花 2024-09-11 10:19:47

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

The pattern I see on html5-boilerplate is:

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

It runs smoothly on different schemes like http, https, file.

酷炫老祖宗 2024-09-11 10:19:47

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

顺便说一句,在更新旧网站时进行了测试,并且也适用于 META REFRESH 的 url= 部分。

As your example is linking to an external domain, if you are using HTTPS then you should verify that the external domain is setup for SSL as well. Otherwise, your users may see SSL errors and/or 404 errors (e.g. older versions of Plesk store HTTP and HTTPS in separate folders). For CDNs, it shouldn't be an issue but for any other website it could be.

On a side note, tested while updated an old website and also works in the url= part of a META REFRESH.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文