Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include two versions of jQuery on a page without affecting old plugins

Our drupal site runs with jQuery version 1.2.1 which we have not upgraded.

The problem is this:

We need to add a new plugin named jQuery Tokeninput, but it's working only in latest jQuery versions. We tried adding the latest jQuery version with old version, but it produces weird results.

My question is, how to include the latest jQuery file without affecting the old jQuery plugins?

like image 580
gvm Avatar asked Dec 20 '22 20:12

gvm


1 Answers

Method #1: (recommended)

You could do something like this:

<script type='text/javascript' src='js/jquery_1.7.1.js'></script>   
<script type='text/javascript'>  
 // In case you wonder why we pass the "true" parameter,
 // here is the explanation:
 //   - When you use jQuery.noConflict(), it deletes
 //     the "$" global variable.
 //   - When you use jQuery.noConflict(true), it also
 //     deletes the "jQuery" global variable.
 var $jq = jQuery.noConflict(true);  
</script>  
<script type='text/javascript' src='js/jquery_1.2.1.js'></script> 

And this way when you want something made with the new version of jquery instead of the $ use $jq.

$jq('.selector').on('click', function(){  
    //do something  
});

Method #2: (might break things on your site - not recommended)

In your template.php file:

<?php
function {theme_name}_preprocess(&$vars, $hook) {
if (arg(0) != 'admin' && $hook == "page") {
// Get an array of all JavaScripts that have been added
$javascript = drupal_add_js(NULL, NULL, 'header');

// Remove the original jQuery library
unset($javascript['core']['misc/jquery.js']);

// Add in our new jQuery library
// We do it this way to keep the includes in the same order
$core = array(
//Alternative jQuery
drupal_get_path('theme', '{theme_name}').'/js/libs/jquery-1.7.1.min.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);
}
}

Be sure to only do this on the frontend of your site. It can mess up admin toolbars if they are dependent on Drupal's version of jQuery.

like image 102
Farhan Ahmad Avatar answered Dec 23 '22 09:12

Farhan Ahmad