Thursday, April 24, 2008

jQuery + prototype in drupal is a go!

jQuery.js and prototype.js, both define $() as a function. This was the reason for the error in the previous blog entry. Didn't figure this out myself, found it in this blog. The good news is that it is taken care of in Drupal 7, and I am using D6 with 1.12.2.1 of jQuery, so I had to use the following workaround -

1) include
var $jq = jQuery.noConflict();
at the beginning of all the javascript files I needed in the misc (and some module) directory (directories).

2) replace every instance of $( with $jq(

This took me to a different problem - I started getting these errors in the files using prototype
"$ is not a function"

I checked the order in which drupal has included the javascript files. prototype.js was defined after jQuery.js
However, according to using jQuery with other libraries, "This will revert $ back to its original library. ", which to me meant, that prototype.js should be declared before jquery.js

This rearrangement is not possible using any combination of drupal_add_js(...), so you must make this change in the template file - page.tpl.php, and if you have enabled multiple templates, then muhuhaha... god onlee to be helping you machi! yeah... change each one of them. Include the prototype script in this fashion

And guess what? It works!! The unfortunate effect of this whole shebang is that prototype.js will be included with each page that gets downloaded if caching is disabled. Which is a big waste of bandwidth and will certainly slow down the site. Perhaps, a better way of handling it would be to include prototype.js on a flag based mechanism like this
Perhaps, but for now, I think I'll just stick to the non-flag mechanism - which is nothing more than a hack. But then we will not have to do this come drupal 7, so waiting eagerly for that one!

No comments: