Sunday, 30 January 2011

Skipping the protocol

I just found out about this incredibly useful trick for loading absolute resources with either http: or https: depending on the protocol with which your page was loaded (to avoid those "mixed content" complaints from browsers).

Amazingly, you can just leave the scheme (protocol) part off the URL entirely. So for instance, if you're loading jQuery from the Google CDN with this path:

<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>
you can load it like this instead:
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script>
If the page that's in is served via http, that path will become
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
If it's https, that will become
https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
E.g., it's a path relative to the protocol (scheme) but in all other ways absolute.

(Naturally, if you load a file via the file: protocol — e.g., locally — it will try to resolve that locally and blow up. But you don't do that, do you?)

Don't trust it? Neither did I, but I haven't found a browser in which it doesn't work, nor apparently have these guys.

And you thought you knew all there was to know about URIs...

1 comment:

Unknown said...

I'm a big fan of leaving off the protocol, yet I've noticed that very few major sites do this. I assume they either don't know or are not confident that all browsers will handle it.

Likewise, I wondered why google-analytics scripts still dynamically append the protocol. It turns out this is needed for some specific IE6 security settings.

And there is a bug in IE7 (and/or 8) such that css files included without protocol are downloaded twice. But for img tags and css urls, I see no reason to include the protocol.