Specify an alternative jQuery library for a particular page on your Drupal site

20-Feb-2009
Filed under: jQuery, Drupal 5.x

Drupal 5.x comes bundled with a fairly outdated version of the jQuery library. Simply downloading the latest version of jQuery and replacing Drupal's jQuery library is not recommended, as this causes compatibility problems with Drupal's own use of jQuery.

Nevertheless, there are times when you might have a requirement to use the latest version of jQuery. For instance, you might want to make use of a jQuery plugin that's not supported by the default version.

I use the code snippet below to selectively include an updated jQuery library (and remove the original) depending on what page on your site is currently being rendered. The snippet needs to be added to your theme's template.php file. If this file does not already exist, you can go ahead and create it. If your template.php already contains a function called _phptemplate_variables, you'll have to integrate what you have with the core of the function below.

All you should have to do to get it working is change 'path/to/new/jquery.js' to the actual path of your new jQuery library, and update the line reading if (arg(0) == 'mypage') { to target your specific page or section.

<?php
function _phptemplate_variables($hook, $vars) {
 
  if (
$hook == 'page') {
   
   
// Make sure we're on the right page
   
if (arg(0) == 'mypage') {
     
     
// Get an array of all JavaScripts that have been added
     
$javascript = drupal_add_js(NULL, NULL, 'header');
     
     
// Remove the original jQuery library and Drupal's JS include
     
unset($javascript['core']['misc/jquery.js']);
      unset(
$javascript['core']['misc/drupal.js']);
     
     
// Add in our new jQuery library and Drupal's JS include
      // We do it this way to keep the includes in the same order
     
$core = array(
       
'path/to/new/jquery.js' => array(
         
'cache' => TRUE,
         
'defer' => FALSE,
        ),
       
'misc/drupal.js' => array(
         
'cache' => TRUE,
         
'defer' => FALSE,
        ),
      );
     
     
// Merge back into the array of core JavaScripts
     
$javascript['core'] = array_merge($javascript['core'], $core);
     
     
// Rerender the block of JavaScripts
     
$vars['scripts'] = drupal_get_js(NULL, $javascript);
     
    }
  }
 
  return
$vars;
 
}
?>