CDN Javascript with SilverStripe

Using a CDN or Content Delivery Network is simple way to add a little performance boost to your website. There are various sources of many Javascript libraries out there on their high performance, dedicated, cookieless domain machines. So why not save your host some pain, let it do a little less, and focus on other things.

In particular I am talking about using a CDN version of JQuery which is shipped with SilverStripe 3 and 2.4 in combination with Prototype. It is used by many of the form fields amoungst other things. So why not replace the locally required JQuery, with something, out there in the wild, that will perform just a little faster.

So here is how it is done, it is very simple. Find yourself the base page controller and find the init method. What we are going to do is block the locally required JQuery and then require the CDN version. Here is one I prepared earlier:

class Page_Controller extends ContentController {

    public static $allowed_actions = array();

    public function init() {
        // Always call the super call init
        // You will get into trouble if you don't

        // Block the local version
        Requirements::block(SAPPHIRE_DIR . '/thirdparty/jquery/jquery.js');

        // Require the CDN version

        // Do more magic such as combining local requirements for JS and CSS ...

That is it folks, nothing to it really ... but a few more rambling notes:

  • Firstly, for SilverStripe 3, you will need JQuery 1.7.2. I haven't tried a later version, I just mirrored the one included with the framework. You might want to double check with other versions of SilverStripe what version of JQuery was packaged with it.
  • Secondly, you will notice in the above required javascript it has not http or https before it. This is intentional. All explained here but if you want the short answer, this stops problems with showing non secure content if your site is viewed as https.
  • Lastly I have used cdnjs, I like this one as they have ... a plethora of pinatas, El Guapo ... I mean a lot of different CSS ans JS libraries but there are alternatives: Google, Microsoft and JQuery.

Hope this saves you a few milliseconds, some bandwidth and maybe even a watt of power. All adds up.