drupal_add_js

Definition

drupal_add_js($data = NULL, $options = NULL, $reset = FALSE)
drupal/includes/common.inc, line 2380

Description

Add a JavaScript file, setting or inline code to the page.

The behavior of this function depends on the parameters it is called with. Generally, it handles the addition of JavaScript to the page, either as reference to an existing file or as inline code. The following actions can be performed using this function:

  • Add a file ('file'): Adds a reference to a JavaScript file to the page.
  • Add inline JavaScript code ('inline'): Executes a piece of JavaScript code on the current page by placing the code directly in the page. This can, for example, be useful to tell the user that a new message arrived, by opening a pop up, alert box etc. This should only be used for JavaScript which cannot be placed and executed from a file.
  • Add settings ('setting'): Adds a setting to Drupal's global storage of JavaScript settings. Per-page settings are required by some modules to function properly. All settings will be accessible at Drupal.settings.
Examples:


  drupal_add_js('misc/collapse.js');
  drupal_add_js('misc/collapse.js', 'file');
  drupal_add_js('$(document).ready(function(){alert("Hello!");});', 'inline');
  drupal_add_js('$(document).ready(function(){alert("Hello!");});',
    array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
  );

Available constants are:

  • JS_LIBRARY: Any libraries, settings, or jQuery plugins.
  • JS_DEFAULT: Any module-layer JavaScript.
  • JS_THEME: Any theme-layer JavaScript.
If you need to invoke a JavaScript file before any other module's JavaScript, for example, you would use JS_DEFAULT - 1. Note that inline JavaScripts are simply appended to the end of the specified scope (region), so they always come last.
  • defer If set to TRUE, the defer attribute is set on the <script> tag. Defaults to FALSE.
  • cache If set to FALSE, the JavaScript file is loaded anew on every page call, that means, it is not cached. Used only when 'type' references a JavaScript file. Defaults to TRUE.
  • preprocess Aggregate the JavaScript if the JavaScript optimization setting has been toggled in admin/settings/performance. Defaults to TRUE.
see drupal_get_js()

Parameters

$data (optional) If given, the value depends on the $options parameter:

  • 'file': Path to the file relative to base_path().
  • 'inline': The JavaScript code that should be placed in the given scope.
  • 'setting': An array with configuration options as associative array. The array is directly placed in Drupal.settings. All modules should wrap their actual configuration settings in another variable to prevent the pollution of the Drupal.settings namespace.
$options (optional) A string defining the type of JavaScript that is being added in the $data parameter ('file'/'setting'/'inline'), or an array which can have any or all of the following keys. JavaScript settings should always pass the string 'setting' only.
  • type The type of JavaScript that is to be added to the page. Allowed values are 'file', 'inline' or 'setting'. Defaults to 'file'.
  • scope The location in which you want to place the script. Possible values are 'header' or 'footer'. If your theme implements different regions, however, you can also use these. Defaults to 'header'.
  • weight A number defining the order in which the JavaScript is added to the page. In some cases, the order in which the JavaScript is presented on the page is very important. jQuery, for example, must be added to to the page before any jQuery code is run, so jquery.js uses a weight of JS_LIBRARY - 2, drupal.js uses a weight of JS_LIBRARY - 1, and all following scripts depending on jQuery and Drupal behaviors are simply added using the default weight of JS_DEFAULT.
$reset (optional) Resets the currently loaded JavaScript.

Return value

The contructed array of JavaScript files.

Related topics

Namesort iconDescription
Input validationFunctions to validate user input.

Code

function drupal_add_js($data = NULL, $options = NULL, $reset = FALSE) {
  static $javascript = array();

  // Construct the options, taking the defaults into consideration.
  if (isset($options)) {
    if (!is_array($options)) {
      $options = array('type' => $options);
    }
  }
  else {
    $options = array();
  }
  $options += drupal_js_defaults($data);

  // Preprocess can only be set if caching is enabled.
  $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;

  // Request made to reset the JavaScript added so far.
  if ($reset) {
    $javascript = array();
  }

  if (isset($data)) {
    // Add jquery.js and drupal.js, as well as the basePath setting, the
    // first time a Javascript file is added.
    if (empty($javascript)) {
      $javascript = array(
        'settings' => array(
          'data' => array(
            array('basePath' => base_path()),
          ),
          'type' => 'setting',
          'scope' => 'header',
          'weight' => JS_LIBRARY,
        ),
        'misc/jquery.js' => array(
          'data' => 'misc/jquery.js',
          'type' => 'file',
          'scope' => 'header',
          'weight' => JS_LIBRARY - 2,
          'cache' => TRUE,
          'defer' => FALSE,
          'preprocess' => TRUE,
        ),
        'misc/drupal.js' => array(
          'data' => 'misc/drupal.js',
          'type' => 'file',
          'scope' => 'header',
          'weight' => JS_LIBRARY - 1,
          'cache' => TRUE,
          'defer' => FALSE,
          'preprocess' => TRUE,
        ),
      );
    }

    switch ($options['type']) {
      case 'setting':
        // All JavaScript settings are placed in the header of the page with
        // the library weight so that inline scripts appear afterwards.
        $javascript['settings']['data'][] = $data;
        break;

      case 'inline':
        $javascript[] = $options;
        break;

      case 'file':
        // Files must keep their name as the associative key so the same
        // JavaScript files can not be added twice.
        $javascript[$options['data']] = $options;
        break;
    }
  }
  return $javascript;
}