Drupal Best Theming Practice for where to put JavaScript (jQuery Mini-series Part 2 of 3)

In D6, you can put a .js file in your base theme directory and it will automatically be loaded by Drupal.

You can also include a js file via an entry in your theme’s .info file:

scripts[] = your_javascript.js

However, I recommend the following:

Consider your JavaScript theme-able like HTML.

  1. It should be able to be themed
  2. Put JavaScript in .js file
  3. Use drupal_add_js() in a theme function
  4. If in a module, call it with hook_init()

As HTML in a theme function / tpl file, calling your JS with a theme function allows theme developers to modify or override your JS in the theme layer.

Here it is in a module:


 * Implementation of hook_init()

function trickoutmysite_init() {


     * Implementation of hook_theme()

 function trickoutmysite_theme($existing, $type, $theme, $path) {

  return array(

        'trickoutmysite_javascript' => array(

      'arguments' => array(),

 * A themable function which uses drupal_add_js to include the js file

function theme_trickoutmysite_javascript() {

  drupal_add_js (drupal_get_path('module', 'trickoutmysite') . '/trickoutmysite.js');



And here is the start of your JavaScript file, which will run your js after your web page (document), has loaded.

// $Id$
// Global killswitch

    if (Drupal.jsEnabled) {
  $(document).ready(function () {

        // Put your javascript in here



  1. Make sure you check out the drupal_ad_js api for its excellent set of options, such as for controlling caching and placement.
  2. Creating a namespace for your theme or module.

Share or Comment via Twitter