Chainsaw on a Tire Swing

Blogging with teeth!

Coolest web development trick I’ve learned in a long time

I can’t tell you how many times WebSanity (my company) has had complications dealing with websites that have a mix of HTTPS & HTTP content. Most web developers have had to mess with that, & it can be a real pain.

So imagine my surprise earlier today when I reading Dave Ward’s “3 reasons why you should let Google host jQuery for you”, when I noticed that his link to Google’s cache of jQuery was as follows:

1
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

Notice anything funky about that hyperlink? It’s missing the http or https! Reading a bit further, Dave links to his earlier article, “Cripple the Google CDN’s caching with a single character”. In that, he elaborates further:

It’s not exactly light reading, but section 4.2 of RFC 3986 provides for fully qualified URLs that omit protocol (the HTTP or HTTPS) altogether. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead.

Put simply, these “protocol-less” URLs allow a reference like this to work in every browser you’ll try it in:

//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js

It looks strange at first, but this “protocol-less” URL is the best way to reference third party content that’s available via both HTTP and HTTPS.

On a page loaded through regular, unencrypted HTTP, script references using that URL will be loaded via HTTP and be cached as normal. Likewise, on a secure page that was loaded via HTTPS, script references targeting that protocol-less URL will automatically load the script from Google’s CDN via HTTPS and avoid the mixed content warning.

Thus, using the protocol-less URL allows a single script reference to adapt itself to what’s most optimal: HTTP and it’s full caching support on HTTP pages, and HTTPS on secured pages so that your users aren’t confronted with a mixed content warning.

I’ve been making websites for almost 20 years, & I never knew this. I’d say I was embarrassed, but I have the feeling almost nobody else knows about it either!

Comments