Protocol-Relative URLs

1 minute read

One of the things I love about programming and development in general is that, no matter how well you think you know something, there's always something that can surprise you.

It doesn't matter what language/domain/stack/toolset you're working with, there are often ways of doing things you haven't thought of.  Sometimes these other ways of doing things are obscure or different to your normal way of thinking.  That's why you've missed them to begin with.

Other times, well...you can't see why you haven't thought of them.  I like it when the surprises are so simple, so immediately effective, that you can be pretty sure you'll remember them from then on.

So to the point.

I'm currently reading Javascript Web Applications.  An excellent book by Alex MacCaw, the author of Spine.  Aside from the book being pretty well written, there are some awesome nuggets of information in there.  In a section discussing the benefits of using a CDN, the following example code is used:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
Just double check that again, did you see it? There's no protocol declared for the script request. This makes it a protocol-relative URL.  The request for the script will be completed over the same protocol as the current page.

Relative URLs? Got that.  Protocol-relative URLs? Why haven't I thought of that before!?

The advantage of this is that you can prevent virtually all annoying mixed content warnings!  Paul Irish has some more info and highlights one or two quirks with IE (of course) and stylesheets.  But the trick can be used for any extra content to load into the page.  It can also be used in pretty much every browser.  IE 3.0 supported it, why didn't I learn this in Web Dev 101?

Tags: ,

Updated:

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading...