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:

About these ads

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s