drupal_add_js

Versions
4.7
drupal_add_js($file, $nocache = FALSE)
5
drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE)
6
drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE, $preprocess = TRUE)
7
drupal_add_js($data = NULL, $options = NULL)

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. When adding inline code, make sure that you are not relying on $ being jQuery. Wrap your code in (function ($) { ... })(jQuery); or use jQuery instead of $.
  • Add external JavaScript ('external'): Allows the inclusion of external JavaScript files that are not hosted on the local server. Note that these external JavaScript references do not get aggregated when preprocessing is on.
  • 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:

<?php

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

?>

Calling drupal_static_reset('drupal_add_js') will clear all JavaScript added so far.

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 &lt;script&gt; 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/config/development/performance. Note that JavaScript of type 'external' is not aggregated. 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.
  • 'external': The absolute path to an external JavaScript file that is not hosted on the local server. These files will not be aggregated if JavaScript aggregation is enabled.
  • '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', 'external' 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.

Return value

The contructed array of JavaScript files.

▾ 27 functions call drupal_add_js()

ajax_process_form in includes/ajax.inc
Add AJAX information about a form element to the page to communicate with JavaScript.
ajax_render in includes/ajax.inc
Render a commands array into JSON and exit.
ajax_test_render in modules/simpletest/tests/ajax_test.module
Menu callback; Copies $_GET['commands'] into $commands and ajax_render()s that.
drupal_add_tabledrag in includes/common.inc
Assist in adding the tableDrag JavaScript behavior to a themed table.
drupal_get_js in includes/common.inc
Returns a themed presentation of all JavaScript code for the current page.
file_ajax_upload in modules/file/file.module
Menu callback; Shared AJAX callback for file uploads and deletions.
filter_form in modules/filter/filter.module
Generates a selector for choosing a format in a form.
install_configure_form in ./install.php
Installation task; configure settings for the new site.
menu_form_node_type_form_alter in modules/menu/menu.module
Implement hook_form_FORM_ID_alter() for the node type form. Adds menu options to the node type form.
node_filter_form in modules/node/node.admin.inc
Return form for node administration filters.
system_clean_url_settings in modules/system/system.admin.inc
Form builder; Configure clean URL settings.
system_performance_settings in modules/system/system.admin.inc
Form builder; Configure site performance settings.
system_user_timezone in modules/system/system.module
Add the time zone field to the user edit and register forms.
template_preprocess_field_ui_field_overview_form in modules/field_ui/field_ui.admin.inc
Theme preprocess function for field_ui-field-overview-form.tpl.php.
theme_profile_admin_overview in modules/profile/profile.admin.inc
Theme the profile field overview into a drag and drop enabled table.
theme_simpletest_test_table in modules/simpletest/simpletest.pages.inc
Theme the test list generated by simpletest_test_form() into a table.
theme_table in includes/theme.inc
Return a themed table.
theme_table_select_header_cell in includes/theme.inc
Returns a header cell for tables that have a select all functionality.
theme_taxonomy_overview_terms in modules/taxonomy/taxonomy.admin.inc
Theme the terms overview as a sortable list of terms.
theme_textarea in includes/form.inc
Theme a textarea form element.
theme_textfield in includes/form.inc
Theme a textfield form element.
update_manager_update_form in modules/update/update.manager.inc
Build the form for the update manager page to update existing projects.
user_admin_settings in modules/user/user.admin.inc
Form builder; Configure user settings for this site.
user_filter_form in modules/user/user.admin.inc
Form builder; Return form for user administration filters.
_batch_progress_page_js in includes/batch.inc
Output a batch processing page with JavaScript support.
_drupal_theme_initialize in includes/theme.inc
Initialize the theme system given already loaded information. This function is useful to initialize a theme when no database is present.
_openid_user_login_form_alter in modules/openid/openid.module

Code

includes/common.inc, line 3692

<?php
function drupal_add_js($data = NULL, $options = NULL) {
  $javascript = &drupal_static(__FUNCTION__, 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;

  // Tweak the weight so that files of the same weight are included in the
  // order of the calls to drupal_add_js().
  $options['weight'] += count($javascript) / 1000;

  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/drupal.js' => array(
          'data' => 'misc/drupal.js',
          'type' => 'file',
          'scope' => 'header',
          'weight' => JS_LIBRARY - 1,
          'cache' => TRUE,
          'defer' => FALSE,
          'preprocess' => TRUE,
        ),
      );
      // Register all required libraries.
      drupal_add_library('system', 'jquery');
      drupal_add_library('system', 'once');
    }

    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;

      default: // 'file' and 'external'
        // Local and external files must keep their name as the associative key
        // so the same JavaScript file is not be added twice.
        $javascript[$options['data']] = $options;
    }
  }
  return $javascript;
}
?>
Login or register to post comments
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.