drupal_add_js

  1. drupal
    1. 5
    2. 6
    3. 7
    4. 8
Versions
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)
8 – 7 drupal_add_js($data = NULL, $options = NULL)

Adds 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 (for example, to tell the user that a new message arrived, by opening a pop up, alert box, etc.). This should only be used for JavaScript that cannot be executed from a file. When adding inline code, make sure that you are not relying on $() being the jQuery function. Wrap your code in

<?php (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 settings 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');
  drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
?>

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

If JavaScript aggregation is enabled, all JavaScript files added with $options['preprocess'] set to TRUE will be merged into one aggregate file. Preprocessed inline JavaScript will not be aggregated into this single file. Externally hosted JavaScripts are never aggregated.

The reason for aggregating the files is outlined quite thoroughly here: http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due to request overhead, one bigger file just loads faster than two smaller ones half its size."

$options['preprocess'] should be only set to TRUE when a file is required for all typical visitors and most pages of a site. It is critical that all preprocessed files are added unconditionally on every page, even if the files are not needed on a page. This is normally done by calling drupal_add_js() in a hook_init() implementation.

Non-preprocessed files should only be added to the page when they are actually needed.

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 associative array with configuration options. The array is merged directly into Drupal.settings. All modules should wrap their actual configuration settings in another variable to prevent conflicts in the Drupal.settings namespace. Items added with a string key will replace existing settings with that key; items with numeric array keys will be added to the existing settings array.

$options (optional) A string defining the type of JavaScript that is being added in the $data parameter ('file'/'setting'/'inline'/'external'), or an associative array. JavaScript settings should always pass the string 'setting' only. Other types can have the following elements in the array:

  • 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, you can also use these. Defaults to 'header'.
  • group: A number identifying the group in which to add the JavaScript. Available constants are:

    The group number serves as a weight: JavaScript within a lower weight group is presented on the page before JavaScript within a higher weight group.

  • every_page: For optimal front-end performance when aggregation is enabled, this should be set to TRUE if the JavaScript is present on every page of the website for users for whom it is present at all. This defaults to FALSE. It is set to TRUE for JavaScript files that are added via module and theme .info files. Modules that add JavaScript within hook_init() implementations, or from other code that ensures that the JavaScript is added to all website pages, should also set this flag to TRUE. All JavaScript files within the same group and that have the 'every_page' flag set to TRUE and do not have 'preprocess' set to FALSE are aggregated together into a single aggregate file, and that aggregate file can be reused across a user's entire site visit, leading to faster navigation between pages. However, JavaScript that is only needed on pages less frequently visited, can be added by code that only runs for those particular pages, and that code should not set the 'every_page' flag. This minimizes the size of the aggregate file that the user needs to download when first visiting the website. JavaScript without the 'every_page' flag is aggregated into a separate aggregate file. This other aggregate file is likely to change from page to page, and each new aggregate file needs to be downloaded when first encountered, so it should be kept relatively small by ensuring that most commonly needed JavaScript is added to every page.
  • weight: A number defining the order in which the JavaScript is added to the page relative to other JavaScript with the same 'scope', 'group', and 'every_page' value. In some cases, the order in which the JavaScript is presented on the page is very important. jQuery, for example, must be added to the page before any jQuery code is run, so jquery.js uses the JS_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js depends on) uses the JS_LIBRARY group and a weight of -19, drupal.js uses the JS_LIBRARY group and a weight of -1, other libraries use the JS_LIBRARY group and a weight of 0 or higher, and all other scripts use one of the other group constants. The exact ordering of JavaScript is as follows:

    • First by scope, with 'header' first, 'footer' last, and any other scopes provided by a custom theme coming in between, as determined by the theme.
    • Then by group.
    • Then by the 'every_page' flag, with TRUE coming before FALSE.
    • Then by weight.
    • Then by the order in which the JavaScript was added. For example, all else being the same, JavaScript added by a call to drupal_add_js() that happened later in the page request gets added to the page after one for which drupal_add_js() happened earlier in the page request.
  • 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; in other words, it is not cached. Used only when 'type' references a JavaScript file. Defaults to TRUE.
  • preprocess: If TRUE and JavaScript aggregation is enabled, the script file will be aggregated. Defaults to TRUE.

Return value

The current array of JavaScript files, settings, and in-line code, including Drupal defaults, anything previously added with calls to drupal_add_js(), and this function call's additions.

See also

drupal_get_js()

▾ 47 functions call drupal_add_js()

ajax_render in includes/ajax.inc
Render a commands array into JSON.
ajax_test_render in modules/simpletest/tests/ajax_test.module
Menu callback; Return an element suitable for use by ajax_deliver().
common_test_js_and_css_querystring in modules/simpletest/tests/common_test.module
Adds a JavaScript file and a CSS file with a query string appended.
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.
drupal_theme_initialize in includes/theme.inc
Initialize the theme system by loading the theme.
file_ajax_upload in modules/file/file.module
Menu callback; Shared Ajax callback for file uploads and deletions.
hook_overlay_child_initialize in modules/overlay/overlay.api.php
Allow modules to act when an overlay child window is initialized.
hook_overlay_parent_initialize in modules/overlay/overlay.api.php
Allow modules to act when an overlay parent window is initialized.
install_configure_form in includes/install.core.inc
Installation task; configure settings for the new site.
JavaScriptTestCase::testAddExternal in modules/simpletest/tests/common.test
Tests adding an external JavaScript File.
JavaScriptTestCase::testAddFile in modules/simpletest/tests/common.test
Test adding a JavaScript file.
JavaScriptTestCase::testAddInline in modules/simpletest/tests/common.test
Test adding inline scripts.
JavaScriptTestCase::testAddSetting in modules/simpletest/tests/common.test
Test adding settings.
JavaScriptTestCase::testAlter in modules/simpletest/tests/common.test
Test altering a JavaScript's weight via hook_js_alter().
JavaScriptTestCase::testDefault in modules/simpletest/tests/common.test
Test default JavaScript is empty.
JavaScriptTestCase::testDifferentGroup in modules/simpletest/tests/common.test
Test adding a JavaScript file with a different group.
JavaScriptTestCase::testDifferentWeight in modules/simpletest/tests/common.test
Test adding a JavaScript file with a different weight.
JavaScriptTestCase::testFooterHTML in modules/simpletest/tests/common.test
Test drupal_get_js() with a footer scope.
JavaScriptTestCase::testHeaderSetting in modules/simpletest/tests/common.test
Test drupal_get_js() for JavaScript settings.
JavaScriptTestCase::testNoCache in modules/simpletest/tests/common.test
Test drupal_add_js() sets preproccess to false when cache is set to false.
JavaScriptTestCase::testRenderDifferentWeight in modules/simpletest/tests/common.test
Test rendering the JavaScript with a file's weight above jQuery's.
JavaScriptTestCase::testRenderExternal in modules/simpletest/tests/common.test
Test rendering an external JavaScript file.
JavaScriptTestCase::testRenderOrder in modules/simpletest/tests/common.test
Test JavaScript ordering.
JavaScriptTestCase::testReset in modules/simpletest/tests/common.test
Test to see if resetting the JavaScript empties the cache.
js_example_js_weights in examples/js_example/js_example.module
js_example_weights implementation.
menu_form_node_type_form_alter in modules/menu/menu.module
Implements hook_form_FORM_ID_alter().
node_filter_form in modules/node/node.admin.inc
Return form for node administration filters.
overlay_close_dialog in modules/overlay/overlay.module
Callback to request that the overlay close as soon as the page is displayed.
overlay_overlay_parent_initialize in modules/overlay/overlay.module
Implements hook_overlay_parent_initialize().
overlay_render_region in modules/overlay/overlay.module
Renders an individual page region.
overlay_trigger_refresh in modules/overlay/overlay.module
Check if the parent window needs to be refreshed on this page load.
system_add_module_assets in modules/system/system.module
Adds CSS and JavaScript files declared in module .info files.
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.
ThemeTableUnitTest::testThemeTableNoStickyHeaders in modules/simpletest/tests/theme.test
If $sticky is FALSE, no tableheader.js should be included.
ThemeTableUnitTest::testThemeTableStickyHeaders in modules/simpletest/tests/theme.test
Tableheader.js provides 'sticky' table headers, and is included by default.
theme_color_scheme_form in modules/color/color.module
Returns HTML for a theme's color form.
theme_profile_admin_overview in modules/profile/profile.admin.inc
Returns HTML for the profile field overview form into a drag and drop enabled table.
theme_simpletest_test_table in modules/simpletest/simpletest.pages.inc
Returns HTML for a test list generated by simpletest_test_form() into a table.
theme_table in includes/theme.inc
Returns HTML for a table.
theme_tableselect in includes/form.inc
Returns HTML for a table with radio buttons or checkboxes.
theme_taxonomy_overview_terms in modules/taxonomy/taxonomy.admin.inc
Returns HTML for a terms overview form as a sortable list of terms.
user_admin_settings in modules/user/user.admin.inc
Form builder; Configure user settings for this site.
_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.

Code

includes/common.inc, line 3943

<?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)) {
      // url() generates the prefix using hook_url_outbound_alter(). Instead of
      // running the hook_url_outbound_alter() again here, extract the prefix
      // from url().
      url('', array('prefix' => &$prefix));
      $javascript = array(
        'settings' => array(
          'data' => array(
            array('basePath' => base_path()),
            array('pathPrefix' => empty($prefix) ? '' : $prefix),
          ), 
          'type' => 'setting', 
          'scope' => 'header', 
          'group' => JS_LIBRARY, 
          'every_page' => TRUE, 
          'weight' => 0,
        ), 
        'misc/drupal.js' => array(
          'data' => 'misc/drupal.js', 
          'type' => 'file', 
          'scope' => 'header', 
          'group' => JS_LIBRARY, 
          'every_page' => TRUE, 
          'weight' => -1, 
          'preprocess' => TRUE, 
          'cache' => TRUE, 
          'defer' => FALSE,
        ),
      );
      // Register all required libraries.
      drupal_add_library('system', 'jquery', TRUE);
      drupal_add_library('system', 'jquery.once', 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;

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