Two forward slashes in a url/src/href attribute

Michael Parkin picture Michael Parkin · Mar 10, 2012 · Viewed 63.6k times · Source

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://?

Answer

vzwick picture vzwick · Mar 10, 2012

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.