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

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

      1. 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

Leave a comment

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