You should serve up assets without a protocol

Why and how you can go about serving up assets without a protocol

Something that recently bit us at ExamTime when we were doing some work that involved proxies and other "thar be dragons" stuff was how after applying some domain changes we would oftentimes get mixed content warnings because we were loading http:// assets onto an https:// domain.

Some browsers handle this news better than others, and because we cannot say for sure how every browser will react, we needed to stop this from happening.

Normally a website can get around mixed content warnings by making a call and doing sweeping changes - an all or nothing sort of approach, this wouldn't work for us for our scenario and in the future it might not work for you, so the following technique is something I think all developers should have in their arsenal.

The solution is a simple one - assets on your site should be loaded without an attached protocol, for example;

<img src="" />

Should really be

<img src="//" />

So, what does this do and what does this afford you?

Basically if you load an asset (and by asset I mean things like, images, CSS files, JavaScript files) without a protocol (the http: bit) then the browser will decide which protocol to use, and the protocol it will decide to use is the one that the main page is being loaded with.

This means that if someone visits all assets will come over https too, which is good for avoiding mixed content warnings.

I have been made aware of one potential downside from a very kind commenter, if you still support IE7 or IE8 then it can download stylesheets twice if no protocol is used. That kind of sucks, but I don't actively support older browsers so I am happy for them to talk a small performance hit.

Another (equally kind) commenter points out that if you are running your files totally locally (using file://) then this will be the protocol adopted throughout, which depending on the rest of your setup might cause problems.

Another issue which I have forgotten to mention but it was brought up in a Reddit comment was that if you are linking to a third party website and you use this method and you send through http traffic but they only support https traffic then you could find yourself with issues, a quick test before you change to // should tell you if this is going to be the case or not.

Recent posts View all


How to ignore Bullet in RSpec tests

Using Bullet during a test can pick up mistakes but also has false negatives; here is an easy way to ignore them


How we used Nokogiri to fix a sizing issue in YouTube's oEmbed

At some point, one of our calls to YouTube's oEmbed endpoint was returning videos way too small; we fixed in in our Rails application by using Nokogiri