Adding javascript to a specific page with template.php and Custom module

Component ID

2055613

Component name

Adding javascript to a specific page with template.php and Custom module

Component type

theme

Maintenance status

Development status

Component security advisory coverage

not-covered

Component created

Component changed

Component body

In case of template.php file.

function mythemename_preprocess_page(&$vars, $hook) {
  if('events' === arg(0)) {
    drupal_add_js(path_to_theme().'/js/events.js');
  }
  
  $vars['scripts'] = drupal_get_js();
}

And, In case of module file

function mymodule_preprocess_page(&$variables) {
  if (isset($variables['node']) && $variables['node']->type == 'book') {
    // Add js
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.awesome.js');
    $variables['scripts'] = drupal_get_js();
  }
}

And, If by home page you mean the front page, then you can implement hook_preprocess_page() in a custom module.

function mymodule_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/mymodule.js');
    $variables['scripts'] = drupal_get_js();
  }
}