Tuesday, March 4, 2014

Drupal add module javascript for a specific page

If like me you prefer to split your interface into modules, and to call each of those modules on separate pages, then one problem you are likely to encounter is the use of jQuery init functions ($(document).ready(function() etc.) in each of those modules. For example, I had separate javascript for a biography page, and for the homepage. Each called its own jQuery init function, and each was incompatible with the other. When loading the biography page I looked for a certain element and then embedded the timeline and biography data fetched from the server into it. This allowed me to leverage existing javascript libraries and to reuse interface code. The drawback, though, is that in Drupal all modules are loaded for each page, and if they contain any javascript it will be executed on page load. Likewise any css files specified in the module's .info file will also be loaded, even though they are not required. Not only is this very inefficient, but it will lead to clashes, as each javascript init function looks for its specific features and fails. So to make it work better and faster you must detect the current page and only load css stylesheets and javascript functions as required. Something like this, in the mymodule.module file will work:

This way both the javascript and css only get loaded when needed, so long as you don't use module names that can occur elsewhere in request uris.

So the moral of the story is: "don't load javascript or css files via a .info file, because they will get loaded on each and every page of your Drupal installation".

No comments:

Post a Comment