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

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.

Last updated 29th July, 2009 - 8:07pm

Authored by Jeff Burnz on