Skip to main content

Login or Register

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.

Comments

#1 Thanks for this to the point solution

thanks, this was a col solution :)

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

Post new comment

The content of this field is kept private and will not be shown publicly.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Adds typographic refinements.

More information about formatting options