Simpler SSL switching with protocol-relative URLs

22 March 2011

Like many developers we like to take advantage of Google's CDN hosted jQuery libraries.

	<script src=""></script>

But this incurs a small additional amount of complexity if the site in question has sections accessed over SSL.

Because the library is being pulled from Google, rather than a relative location on your server, you need to use the absolute URL including protocol, domain and path. This is all well and good, until you access a page in the secure area of your site, at which point your browser will more or less obtrusively warn you (Internet Explorer typically with an alert pop-up) that you are accessing unsecured content over a secure connection.

Screen shot of Internet Explorer warning dialogue box

Google do support SSL on their CDN, so it's just a question of detecting that the page request is using the secure layer and switching to https rather than http when including the library. This can be done server side as follows

		<script src="http#( ( cgi.https IS 'on' ) ? 's' : '' )#://"></script>

Protocol-relative URLs

However, as I learnt today from Chris Tierney's blog, there is a simpler way of approaching this that doesn't require any logic.

You can simply drop the protocol, i.e. "http", from the URL and the browser will use whatever the current request happens to be using:

	<script src="//"></script>

In 15+ years of web development this is the first I'd heard of this apparently basic aspect of URL syntax.

Paul Irish provides more detail and important caveats about where it's not appropriate to use (especially on local setups).


  • Formatting comments: See this list of formatting tags you can use in your comments.
  • Want to paste code? Enclose within <pre><code> tags for syntax higlighting and better formatting and if possible use script. If your code includes "self-closing" tags, such as <cfargument>, you must add an explicit closing tag, otherwise it is likely to be mangled by the Disqus parser.
Back to the top