Two forward slashes in a url/src/href attribute

HtmlHttpHttpsRelative Url

Html Problem Overview


> Possible Duplicate:
> URI starting with two slashes … how do they behave?
> Absolute URLs omitting the protocol (scheme) in order to preserve the one of the current page
> shorthand as // for script and link tags? anyone see / use this before?

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>

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

Html Solutions


Solution 1 - Html

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.

Solution 2 - Html

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael ParkinView Question on Stackoverflow
Solution 1 - HtmlvzwickView Answer on Stackoverflow
Solution 2 - HtmlRadu CugutView Answer on Stackoverflow