Protocol-relative URLs in HTML attributes

Having worked on a few sites where only some of the pages are SSL-secured, I can say that ensuring all the external assets in the page are loaded using the HTTPS protocol to prevent security warnings (primarily in Internet Explorer, damn it to hell) relating to the mixing of secure and non-secure elements is a relatively arduous task. There is, however, a workaround that can be used when creating the site’s master page / main template – protocol-relative URLs in the HTML tags that load the aforementioned external assets.

Where the assets are being loaded from the same host, normal relative addresses can be used to ensure that they are loaded using the same protocol as the page itself, viz.:

<img src="/images/happysmileyface.gif" />

or

<img src="happysmileyface.gif" />

to load it from the same folder as the page itself. In both cases, since the hostname is omitted, the protocol to be used is assumed by the browser to be that of the page itself. But, what happens if we need to load an asset from another host? This has been pertinent in two specific areas of template work I’ve been involved in recently:

  1. Addition of tracking and conversion tags, such as Google Analytics and WebTrends
  2. Loading static assets from a content delivery network

Let’s say we’re loading an image file into a master page from a CDN, which of course has a different host name. Normally, we’d set the tag’s SRC attribute to be an absolute address:

<img src="http://cdn.gravysite.com/images/happysmileyface.gif" />

This is fine as long as the pages/views using the master page are all being served over HTTP. When we want to create a page that uses the master page but which is SSL secured, however, we will see IE and other browsers complain that there is a mixture of secure and non-secure elements. There is a way around this, however, using a more obscure URL syntax:

<img src="//cdn.gravysite.com/images/happysmileyface.gif" />

The protocol part of the URL is left off altogether. Simple as that. This works because, similarly to how browsers use the qualities of the base page to work out where to load assets from when the hostname is omitted in relative addresses, they are able to work out which protocol to use when that is omitted too.

WARNING: Never use this URL format in HTML destined for email templates, as Windows mail clients will interpret those leading slashes as an attempt to load assets from a network location. Not pretty!

January 4, 2009

How to move a Subversion repository from one server to another

October 1, 2008

Translate text in MSN Messenger

September 6, 2008