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

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 ('core', 'module' and 'theme'): Adds a reference to a JavaScript file to the page. JavaScript files are placed in a certain order, from 'core' first, to 'module' and finally 'theme' so that files, that are added later, can override previously added files with ease.
  • 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.
  • 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. The settings will be accessible at Drupal.settings.


zzolo’s picture

A few quick examples of how to use this function:

  // This will add a JS file to your head (specifically the $scripts variable in page.tpl.php)
  drupal_add_js(drupal_get_path('module', 'my_module') . '/my_module.js');

  // This add inline JS to the head of the document
  drupal_add_js('alert("Hello!")', 'inline');

  // This will add variables in the Drupal.settings object
  drupal_add_js(array('my_module' => array('my_setting' => 'this_value')), 'setting');

If you need to add an external JS file to your site, you should probably look at http://api.drupal.org/api/function/drupal_set_html_head/6

Sinan Erdem’s picture

My module cannot add any js file with:

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

I checked that the path is correct and the file has correct permissions. Is there another thing to do before it?

Edit: I found out that js optimization was enabled and it prevented the new file from loading. (admin/settings/performance). I disabled it for a the time...

Madbreaks’s picture

A useful if somewhat confusing feature of this function is that, at least with settings (I haven't tried w/ other types), calls to this function are additive. Consider the following:

drupal_add_js(array('myNamespace' => array('widgets' => array('foo')), 'setting');
drupal_add_js(array('myNamespace' => array('widgets' => array('bar')), 'setting');
drupal_add_js(array('myNamespace' => array('widgets' => array('baz')), 'setting');

If you examine the internal $javascript array after these calls, you'll see that each widget is added separately, they are not part of the same scope within the array. However, when the JS is themed, they will be. Based on the above example, here's what the client-side JS will look like:

jQuery.extend(Drupal.settings, { ..."myNamespace": { "widgets": [ "foo", "bar", "baz" ] }, ... });


doublejosh’s picture

Looking for a way to avoid this.
If a setting gets added on each node load then the same setting can get several entries if the node is loaded more than once per page (though it's data is cached.)

Just used $op = 'view' for now since that MOSTLY only happens once per page in my node example... but still think there should be a way to do some sort of drupal_add_js_once().

beefheartfan’s picture

If you just pass NULL values for $data and $type into the drupal_add_js function it will return an array of all the current javascript definitions on the page.
Within that array is a 'setting' array that contains all the current settings. So you can include settings only if they don't exist by doing something like this....

// Get all the current javascript information
$current_js = drupal_add_js(NULL, NULL, 'header');

// Filter the information down to just the settings.
$current_js_settings = $current_js['setting'];

// Initialize a flag to determine if the setting is already defined.
$mysetting_isset = false;

// Loop through each setting 
foreach ($current_js_settings as $current_js_setting) {
        // Check to see if the setting is defined in the array (change 'mysetting' to whatever setting you want)
	if (array_key_exists('mysetting', $current_js_setting)) {
                // We found it so set the flag to true.
		$mysetting_isset = true;

// Check to see if the flag is still false.
if (!$mysetting_isset) {
        // The flag is false, so the setting is not defined. Include your drupal_add_js call here!
	drupal_add_js(array('mysetting' => 'something'), 'setting', 'header');

I hope this helps!

lyosef’s picture

I did a search for "How to add a JavaScript file to a single page" in Drupal 6 and wound up here. The code which takes up most of the page appears to be merely the re-print of the commons.inc file included with the download of Drupal.

I have been searching for many days and have not yet found a straight-forward answer to my question--which is so easily done in HTML or PHP.

If you know how to simply add a JavaScript file to a single Drupal I would be so grateful if you would share it. Note: Simply referring to the file as an include file does not work.

itserich’s picture

I would like to add the following javascript to a page or custom block, can not figure out how.

<!-- iSpeech Player Code-->
<script type="text/javascript" src="http://www.ispeech.org/embed/280263/2215009?autostart=no"></script><noscript><embed src="http://www.ispeech.org/ispeech.swf" quality="high" flashvars="autostart=no&playlist=http://www.ispeech.org/downloads/280263/2215009/audio.xml" type="application/x-shockwave-flash" width="204" height="35" pluginspage="http://www.macromedia.com/go/getflashplayer"><a href="http://www.ispeech.org/">Free Text to Speech</a></noscript>
<!-- iSpeech Player Code End -->
sleeping_at-work-’s picture

You can add in your theme (http://drupal.org/node/171205#scripts) or use drupal_add_js (http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_ad...) if you wish to add it in a custom module

Gabriel R.’s picture

Would it be possible to return the resulting JS code instead of adding it to the page?
It would be useful to assign it to a variable, like:

 $theCode = drupal_add_js("$('#link-newpass').insertAfter('#edit-pass-wrapper');","return");
// ...many lines later 
print $theCode;

Maybe there is a scope setting that can be used for this already?

anon’s picture

Use the "type" = "Inline" for that kind of stuff.

hutch120’s picture

Many people may also wish to run some javascript just after the page loads. You could use code similar to the following.

In your php use a line like this (replace elements as appropriate):

drupal_add_js(drupal_get_path('module', 'your_module_name').'/run_after_page_loads.js', 'module');

In the run_after_page_loads.js file add code like this:

Drupal.behaviors.run_after_page_loads = function (context) {
    // Some jQuery that runs once the page loads.

More technical and indepth description along with passing data from PHP to javascript here:

gagarine’s picture

"If the first parameter is NULL, the JavaScript array that has been built so far for $scope is returned."

Note than the array build so far is also deleted!

kenorb’s picture

To modify the javascript that gets output to the page, try:
which defines hook_js_alter() which is part of Drupal 7

alexweber’s picture

This is apparently un-documented but you can also get external links to work in Drupal 6 by doing this: drupal_add_js('http://www.my-external-script.js', 'module', 'header', FALSE, TRUE, FALSE);

JThan’s picture

Does not work for me. It gives the base_path + the external path, so it wont find the script.

wrg20’s picture

I just saved whatever javascript it was locally in a folder like /scripts/ then referenced it. drupal_add_js('sites/[SITENAME]/themes/[YOURTHEME]/scripts/[YOURJSFILE].js', 'module', 'footer', FALSE, TRUE, FALSE);