url/src/href 属性中的两个正斜杠 [英] Two forward slashes in a url/src/href attribute

查看:118
本文介绍了url/src/href 属性中的两个正斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
URI 以两个斜线开头 …他们的行为如何?
绝对网址省略协议(方案)以保留当前页面之一
简写为//脚本和链接标签?有人看过/使用过吗?

当我注意到 HTML5 Resethttps://github.com/murtaugh/HTML5-Reset/blob/master/index.html#L113" rel="noreferrer">以下行:

I was looking through the source of HTML5 Reset when I noticed the following line:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>

为什么 URL 以两个正斜杠开头?这是 http:// 的简写吗?

Why does the URL start with two forward slashes? Is this a shorthand for http://?

推荐答案

两个正斜杠"是现在正在使用的任何协议"的常用简写.

最广为人知的协议相对 URL",当元素(例如示例中的 JS 文件)可以从 httphttps<加载时,它们特别有用./代码> 上下文.通过使用协议相对 URL,您可以避免实现

The "two forward slashes" are a common shorthand for "whatever protocol is being used right now".

Best known as "protocol relative URLs", they are particularly useful when elements — such as the JS file in your example — could be loaded from either a http or a https context. By using protocol relative URLs, you can avoid implementing

if (window.location.protocol === 'http:') {
    myResourceUrl = 'http://example.com/my-resource.js';
} else {
    myResourceUrl = 'https://example.com/my-resource.js';
}

整个代码库中的逻辑类型(当然,假设 example.com 上的服务器能够通过 httphttps).

type of logic all over your codebase (assuming, of course, that the server at example.com is able to serve resources via both http and https).

一个突出的现实世界的例子是 Magento 电子商务引擎:出于性能原因,商店的页面默认使用纯 http,而结账是启用 https.

A prominent real-world example is the Magento E-Commerce engine: for performance reasons, the shop's pages use plain http by default, whereas the checkout is https enabled.

当硬编码资源(即网站标题中的促销横幅)被非协议相对 URL(即 http://example.com/banner.jpg)引用时,客户到达 https 启用的结帐将受到相当不友好的欢迎

When hard-coded resources (i.e. promotional banners in the site's header) are referenced by non protocol relative URLs (i.e. http://example.com/banner.jpg), customers reaching the https enabled checkout will be greeted with a rather unfriendly

此页面上存在不安全元素"

"there are insecure elements on this page"

提示 - 正如您想象的那样,这会让一般不精通技术的人望而却步.

prompt - which, as you can imagine, throws the average non-tech-savvy person off.

如果上述资源是通过 //example.com/banner.jpg 引用的,浏览器会负责预先准备正确的协议.

If the aforementioned resource is referenced via //example.com/banner.jpg though, the browser takes care of prepending the proper protocol.

tl;dr:即使是最轻微的混合 http/https 环境的可能性,也只需使用双斜杠/协议相对 URL 来加载您的资源——假设提供内容的主机同时启用了 http 和 https.

这篇关于url/src/href 属性中的两个正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆