9

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...

6

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.

|improve this answer|||||
6

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).

|improve this answer|||||
2

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

OR

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.

|improve this answer|||||
0

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.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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