Protocol Relative URLs

One little gem I recently encountered is protocol-relative URLs. This solves the headaches of the age-old problem of creating URLs which work whether you’re in SSL mode or normal http. For example take the following image :

<img src="http://some-domain.com/images/logo.png">

If the browser is viewing the current page in through HTTPS, then IE will throw the famous “This Page Contains Both Secure and Non-Secure Items” error message. To prevent that from happening we can use protocol-relative urls. So the above will be coded as given below.

<img src="//some-domain.com/images/logo.png">

This will reference the ‘logo.png’ relative to the page protocol, whether ‘http’ or ‘https’. It’s just like a regular URL except that you leave out the protocol prefix. So if the document containing that URL is requested over HTTPS then that URL will be ‘https://some-domain.com/images/logo.png’ and over HTTP the URL will be ‘http://some-domain.com/images/logo.png’

Technically, this is called a “network-path reference” according to RFC 3986, and works in all the browsers, including older versions of IE.

One caveat though, Internet Explorer 7 & 8 will download stylesheets twice if the http(s) protocol is missing. See Steve Souders.

Still one place you can find this useful is when loading resources from the Google CDN. This will ensure that no security warnings are generated by IE.

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