Adding JS/CSS from a Drupal Module
I'm porting over the Panel Navigation for Bentley University into a Drupal Module. The navigation is currently visible on http://www.bentley.edu. One of the challenges was loading it in Drupal on every page load. The module uses a combination of hooks and adds a variable to _phptemplate_variables in the theme.
The one element that gave me the most problems was one of the easiest to solve. I kept trying to call drupal_add_js() and drupal_add_css() from within the function that renders the theme output. The HTML output would render fine but I could not see the JS/CSS anywhere. After digging around the forums it became apparent I needed to fire off the inclusion of the js and css at a different hook.
Initially I added the functions to hook_init(). Apparently this can cause problems as not all Drupal functions are available from the bootstrap process. On further reading the hook_menu function was recommended. This was very easy, and seems like a relatively clean way of doing things. Keep in mind this is all using D5. My understanding is D6 and D7 have more elegant solutions.
/** hook_menu implementation */ function mymodule_menu($may_cache) { if(!$may_cache) { _mymodule_init(); } } /** js/css init function **/ function _mymodule_init() { $path = drupal_get_path('module','mymodule'); drupal_add_js($path . '/js/jquery.someplugin.js'); drupal_add_js($path . '/js/mymodule.js'); drupal_add_css($path . '/css/mymodule.css'); }
I'm always on the lookout for better ways of doing things so this post may be updated. For the time being this was nice, quick and easy!
- Login to post comments