Add JavaScript to Drupal 6 for the front page only

This cropped up in the Drupal forums today, again, so I dug this bit of code out since I was messing about with recently. If you want to load a .js file only for the homepage there's a couple of ways of doing it.

First in template.php you can simply add the following - which assumes you have saved the .js file in your theme folder. Adjust the path to suit (for example /js/myscript.js).

if (drupal_is_front_page()) {
  drupal_add_js(drupal_get_path('theme', 'mytheme').'/myscript.js', 'theme');
}

This is nice since you can add a few more parameters to it - see the full story here http://api.drupal.org/api/function/drupal_add_js

The other more brutal way is to conditionally load the script directly in the head of page.tpl.php, such as:

<?php if ($is_front): ?>
  <script type="text/javascript" src="/sites/all/themes/mytheme/myscript.js"></script>
<?php endif; ?>

I, like a few others, made the immediate assumption that you could conditionally load a JavaScipt file using vars in a preprocessor function, but I am yet to get this to work. If you know of a way, I'd love to know.

Submitted by Jeff Burnz on

Comments

Anonymous's picture

extensions....

Nice, and simple... I'm someone who know very little in php, but how would you add an "if" for multiple pages? e.g. node/1, node/2 = `

<?php
if ($is_node/1 node/2):
?>
` ? thanks.

Brian's picture

The reason you can’t use

The reason you can't use drupal_add_js() in a preprocess function, is because $vars['script'] (the actual HTML output for the head) is rendered in template_preprocess_page(), which is called before all user preprocess functions.

Personally I don't understand why this is; the whole point of preprocess functions is to accomplish things BEFORE RENDERING! Why can't the 'script' var be rendered at the last second? Surely nothing needs it in string form except the actual browser itself.

You can get around this problem by re-rendering the script var with $variables['scripts'] = drupal_get_js();, but this is inefficient.

There's a discussion of this issue here:

http://www.drupaler.co.uk/blog/joys-preprocessing/70

Darren's picture

@Brian, why re-render when

@Brian, why re-render when you can just append (or prepend if necessary), eg.

$variables[‘scripts’] .= '<script type="text/javascript" src="/sites/all/themes/mytheme/myscript.js"></script>';