Two forward slashes in a url/src/href attribute [duplicate]
The "two forward slashes" are a common shorthand for "request the referenced resource using whatever protocol is being used to load the current page".
Best known as "protocol relative URLs", they are particularly useful when elements — such as the JS file in your example — could be served and/or requested 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 content through both http
and https
).
A prominent real-world example is the Magento 1.X E-Commerce engine: for performance reasons, the category and product pages use plain http
by default, whereas the checkout is https
enabled.
If some resources (e.g. promotional banners in the site's header) are referenced via non protocol relative URLs (i.e. http://example.com/banner.jpg
), customers reaching the https
enabled checkout are greeted with a rather unfriendly
"there are insecure elements on this page"
prompt - which, one can safely assume, isn't exactly great for business.
If the aforementioned resource is referenced via //example.com/banner.jpg
though, the browser takes care of loading it via the proper protocol both on the plain http product/category pages and in the https-enabled checkout flow.
tl;dr: With even the slightest possibility of a mixed http/https environment, just use the double slash/protocol relative URLs to reference resources — assuming that the host serving them supports both http and https.
It will automatically add https or http, depending on how the request was made.