Drupal 7 – Add Javascript files on specific paths by template.php

In my previous post, Drupal 7 – Add Javascript files on specific paths by custom module, we try to add .js files for specific paths by creating a custom module. Actually we could implement the same feature by using the theme template.php. Here is an example.

1. Create the js/eureka.js in your theme folder.
js/eureka.js

jQuery(document).ready(function() {
  alert('halo world');
});

 

2. Add the template_preprocess_html() function in the theme template.php as follow.
template.php

function <THEME>_preprocess_html(&$variables) {
  $theme_path = path_to_theme();
  $url = request_uri();
  if ($url == '/home') {
    drupal_add_js($theme_path . '/js/eureka.js');
  }
}

 

Done =)

Reference:

5 thoughts on “Drupal 7 – Add Javascript files on specific paths by template.php”

Leave a reply to ykyuen Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.