Absolute URLs and HTTP/HTTPS

Posted on June 8, 2011 by Frederik Vig in Web design

Here’s a neat little trick I saw after browsing the HTML 5 Boilerplate code. Instead of specifying a protocol (HTTP/HTTPS) when adding absolute URLs to resources like jQuery on Google CDN you only need to specify // followed by the rest of the URL. The browser will then automatically use the correct one based on the protocol of the site the user is on right now. Note that this only works if both the HTTP and the HTTPS version of the URL exists.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>

Can be written like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>

If I had this code on https://www.frederikvig.com, the browser would send a request to the URL: https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js.

Related Posts: