Drupal 7 – Add Javascript files on specific paths by custom module

In the past, i always added js files on theme level. This is not a good approach because the aggregated theme js will be quite large and it is loaded on every pages even js code is not used.

So this time i try to add the js on specific path only when it is needed. This is done by creating a custom module. Let’s name the custom module eureka_js.

1. Inside the eureka_js module folder, we have the following files.

  • js/eureka.js
  • eureka_js.info
  • eureka_js.module


 

2. js/eureka.js

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

 

3. eureka_js.info

name = Eureka JS
description = Add javascript files on specific paths.
core = 7.x
package = Eureka
version = 7.x-1.0

 

4. eureka_js.module

<?php

function eureka_js_html_head_alter(&$head_elements) {
  $url = request_uri();
  $path = drupal_get_path('module', 'eureka_js');
  if ($url == '/home') { // if /home is requested.
    drupal_add_js($path . '/js/eureka.js');
    /* Uncomment the following line for inline javascript */
    //drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
  }
}

 

4. The eureka.js will be loaded only when accessing the /home url. You can manage all js files on different paths by editing the eureka_js.module.
 

Done =)

Update @ 2012-02-15: You can also implement the same feature by using template.php. Please refer to Drupal 7 – Add Javascript files on specific paths by template.php

About these ads

10 thoughts on “Drupal 7 – Add Javascript files on specific paths by custom module

      1. Mike

        Might be worth adding the code for a template.php version :)

        I don’t have the code to hand right now but it shouldn’t be to hard just modify the theme processor.

        Like

  1. Pingback: Drupal 7 – Add Javascript files on specific paths by template.php | Eureka!

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