I would like to know what is the best way to add a JavaScript file into a specific page basing on the content type. For example, I want to add this:

<script type='text/javascript' src='http://maps.google.com/maps/api/js?sensor=false'></script>

So far, what I have done is using this way to add into my specific content type. For the map_page content type, I adde the below two line of code in page--map_page.tpl.php.

drupal_add_js("http://maps.google.com/maps/api/js?sensor=false", 'external');
$scripts = drupal_get_js();

Is there any other better way? if possible can give some example, currently not really understand well...

4 Answers 4


I can't comment on the proper Drupal 7 equivalent, but in Drupal 6 sites I do this in a template_preprocess_page.

I will have some logic to make the decision (either based on arg() or page_manager_get_current_page() from panels), and then prepend $vars["scripts"] with the external script. I prepend so that I don't run into dependency trouble with any local scripts.

I will also sometimes set up a new region called $global_scripts for thinks like Google API and SWFObject that I want to load from a CDN, and this gets printed out before $scripts in the page template.

To be honest, though I normally have all JS on all pages so that the files get cached.


Since Drupal won't let you redefine template_preprocess_node (because it's already defined in node.module), I added a preprocessor function in my custom module:

function mymodule_preprocess_node(&$vars) {
  if ($vars['type'] == 'my-node-type') {
    drupal_add_js(drupal_get_path('module', 'mymodule') . '/myjs.js');

I used preprocess_node rather than preprocess_page because it's easier to get to the node type. If you actually reference a javascript file, then it will be automatically cached (see Parameters section).


you could also use hook_node_view check for the content type and then add the js in the way you are doing already.


If you have a field which outputs the information which will use the JS use a preprocessor there to add the js, so the js include is dependent on the field displaying the map rather than the content type.


A simple solution is to just place the add_js:

  drupal_add_js('drupal_get_path('module', 'mymodule') . '/myjs.js');

in the page/node template.php.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.