14 February 2014

According to Royal Pingdom, approximately 54% of the top 10k sites use jQuery, and approximately 25% of sites that use jQuery rely on the Google CDN. Neither of those statistics are concrete metrics of the number of users with cached versions of jQuery as served by Google, but it is reasonable that a healthy number of active web users have a primed browser cache. Even if you were pessimistic and restricted your analysis to the top 100 web sites (25% use jQuery), the best information you have is that Google is still the most popular CDN. Of course, the analysis does not make that clear, but no alternatives are suggested. So how do you leverage this cache insight with your Drupal 7 web site?

The Solution

For a zero-impact jQuery replacement, you should simply replace the misc/jquery.js with an external reference to the Google CDN. Fortunately, the hook_js_alter function gives you the ability to do just that. After you create your hook, make sure that you Flush all caches. Here is the hook you will need to add to a custom module:

function mymodule_js_alter(&$js) {
  // Use Google CDN for jQuery.
  $js['misc/jquery.js'] = array(
    'group' => JS_LIBRARY,
    'weight' => -20,
    'version' => '1.4.4',
    'every_page' => true,
    'type' => 'external',
    'scope' => 'header',
    'cache' => false,
    'defer' => false,
    'preprocess' => false,
    'data' => '//ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js',

blog comments powered by Disqus