Search code examples
drupaldrupal-7drupal-modules

Load CSS and JS files only to a specific module Drupal


I’m developing a custom module, but need that only in the page where I use this module add some CSS and JavaScript files, I know how to do this from template.php using a condition to specific node, but I need do it more generic, that the condition can stay in .module file, or some similar solution.

I have a little code in my .module file:

function mymodule_init() {
    $url = request_uri();
    $path = drupal_get_path('module', 'module_name');
    if ($url == 'xxxx') { 
        drupal_add_js($path . '/js/animations.js');
    }
}

This work very well, but I’m limiting, because I need know the URL where the module will used.


Solution

  • Rather than checking for the URL, you should add your drupal_add_js when you initialize the code your module will be using on a given page.

    For example, if you are adding a block, you could add it to hook_block_view. If you're adding a theme template, you could do it in hook_preprocess for that theme template.