Two forward slashes in a url/src/href attribute [duplicate]

大憨熊 提交于 2019-11-26 10:16:37

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';
}

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

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.

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.

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

tl;dr: With even the slightest possibility of a mixed http/https environment, just use the double slash/protocol relative URLs for loading your resources — assuming that the host serving the content is both http and https enabled.

It will automatically add https or http, depending on how the request was made.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!