drupal_add_js($data = NULL, $options = NULL, $reset = FALSE)
drupal/includes/common.inc, line 2380
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:
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:
$data (optional) If given, the value depends on the $options parameter:
The contructed array of JavaScript files.
| Name | Description |
|---|---|
| Input validation | Functions to validate user input. |
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;
}