Paul Irish

Making the www great

The Protocol-relative URL

Update 2014.12.17:

Now that SSL is encouraged for everyone and doesn’t have performance concerns, this technique is now an anti-pattern. If the asset you need is available on SSL, then always use the https:// asset.

Allowing the snippet to request over HTTP opens the door for attacks like the recent Github Man-on-the-side attack. It’s always safe to request HTTPS assets even if your site is on HTTP, however the reverse is not true.

More guidance and details in Eric Mills’ guide to CDNs & HTTPS and digitalgov.gov’s writeup on secure analytics hosting.

There’s this little trick you can get away with that’ll save you some headaches:

1
<img src="//domain.com/img/logo.png">

If the browser is viewing that current page in through HTTPS, then it’ll request that asset with the HTTPS protocol, otherwise it’ll typically* request it with HTTP. This prevents that awful “This Page Contains Both Secure and Non-Secure Items” error message in IE, keeping all your asset requests within the same protocol.

*Of course, if you’re viewing the file locally, it’ll try to request the file with the file:// protocol.

We use this trick in the HTML5 Boilerplate for a clever request of jQuery off the Google CDN:

1
2
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.4.2.js"%3E%3C/script%3E'))</script>

Technically, this is called a “network-path reference” according to RFC 3986. Oh and if you want to be truly correct, you’ll use the term “scheme” instead of “protocol” when talking about URLs.

This trick also works fine in CSS:

1
.omgomg { background: url(//websbestgifs.net/kittyonadolphin.gif); }

… assuming the site you’re pointing to has this asset available on both HTTP and HTTPS.

Caveat: When used on a <link> or @import for a stylesheet, IE7 and IE8 download the file twice. All other uses, however, are just fine.

Thx to miketaylr, ralphholzmann, annevk for smarts on this, and ajaxian, where I think I learned it like 4 years ago? maybe?

2011.01.23: But… what about using this on the Google Analytics snippet?

Yes of course, wouldn’t that be nice… So I worked with the Google Analytics javascript lead developer (God, I love working at google) to see if we could do this… turns out we can’t. There is an edgecase bug in IE6 that causes a dialog to blow up… under some security settings (unsure if they are default) when requesting from the non-‘ssl’ subdomain. screenshot here. So feel free to take 40 bytes off your GA snippet if you don’t care about IE6.. otherwise you’re gonna need that ternary operator. :)

2011.12.24. Eric Law (from the IE team) chimes on why IE6 doesnt play well GA…
The reason this doesn’t work in IE6 is that the server is using SNI to deduce what certificate to return. XP (and thus IE6) doesn’t support SNI in the HTTPS stack. See for details.

Comments