Protocol Neutral CSS and JS references

Web Dev 9 April 2013 | 2 Comments

My coworker blew my mind this morning. Anyone working with secure sites knows that there's often security flags thrown if you're referencing a file via http:// when the site is under https://. To avoid these, in the past I have always done an if/else in whatever language the site was written. For example:

CODE:
  1. /* pseudocode */
  2. if(IsSecureConnection){
  3.     <link href="https://fonts.googleapis.com/css?family=Cabin&v1" rel="stylesheet" type="text/css" />
  4. }else{
  5.    <link href="http://fonts.googleapis.com/css?family=Cabin&v1" rel="stylesheet" type="text/css" />
  6. }

In debugging some code on our site, I noticed that the aforementioned stylesheet was only linked in the Secure check, and forgotten in the else.

Lo and behold, you can avoid these confusions by including your external references without the protocol included. That's right, drop off the http: and just leave two slashes and the link, as follows:

CODE:
  1. <link href="//fonts.googleapis.com/css?family=Cabin&v1" rel="stylesheet" type="text/css" />

It works perfectly and you can simplify your server code. C'est magnifique! I'm not sure about older browsers, so if you run into an issue, leave a comment and I'll note my post accordingly.

Share and Enjoy:
  • del.icio.us
  • Digg
  • Twitter
  • Google Bookmarks
  • StumbleUpon
  • Facebook
  • email
  • Print

2 Responses on “Protocol Neutral CSS and JS references”

  1. Tony White says:

    Great tip. I first noticed this on Google's documentation for linking to their hosted versions of jquery:
    https://developers.google.com/speed/libraries/devguide
    Good find.

  2. Jennifer says:

    Awesome! Thanks for that link, I had never seen this technique used before. Need to read more!

Leave a Reply