Adding javascript to specific node/url in drupal

This was in one of the module I’ve written in Drupal and I thought it would be useful to share.

The Problem: I wanted to dynamically add javascript file to a specific url under Drupal. The benefit would been that I did not have to include the .js file for the whole site therefore optimize the performance of site. Not to mention that it by including the javascript file in a specific url, it will not interfere with other scripts, etc.

To review, the function to add javascript in drupal is

drupal_add_js() (http://api.drupal.org/api/function/drupal_add_js/)

However, this function will add a javascript file or script to the head section on all of the drupal path/urls, making it clunky.

The Solution:


// The function passes in a parameter which is the url you want to check
// It will return true if the url the user is browsing matches the url you are trying to
// act on
function module_name_helper_is_page($check_url)
{
	global $base_url;

	$page_url = module_name_helper_get_curl_url();

	if(!stristr($page_url, $check_url))
	{
		return FALSE;
	}
	else
	{
		return TRUE;
	}
}

/*
 * This function simply returns the current url of the web page
*/
function module_name_helper_get_curl_url()
{
	$pageURL = 'http';
	if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
	$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
	$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
	} else {
	$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
	}

	return $pageURL;
}

To put it into action, say we wanted to only add a javascript file to the user registration page, here would be what it looks like. (By the way, module_name stands for the module you are writing)

if(module_name_helper_is_page($base_url . 'user/register'))
{
     drupal_add_js(drupal_get_path('module', 'module_name') .'/yourjavascript.js', 'module', 'header');
}

Cheers!

One Response to “Adding javascript to specific node/url in drupal”

  1. DrunkMunki says:

    thats probably the longest way i have seen it done.

    why not check out http://drupal.org/node/304178

Leave a Reply