I have a field which is used in a nodeblock, and only appears on a few select pages. This however will vary throughout the lifetime of the website so I've been looking for a way to insert the Javascript this field requires only when it's present. Additionally, the field can appear more than once on any given page.

Looking at drupal_add_js, I can't see that it provides a way to only include JS once. Using this I was hoping that I could just call it in the field--field-name.tpl.php file for that field but as it occurs multiple times, the JS is included more than once.

I've looked at the module JS Injector, but that's just page specific and just calls the aforementioned function. This wouldn't help me because every time a new block is added somewhere, the list of pages including the JS would also need to be updated.

Is there a way I can include a JS file just once in Drupal?

  • 3
    Are you familiar with the php static keyword? If not put that in on google, it's ideal for solving your problem – Clive Aug 7 '13 at 13:20
  • Are you trying to add a JS file once or some inline JS once? – mpdonadio Aug 7 '13 at 13:31
  • 2
    A JS file once. @Clive I assume you mean something like static $done; if(!$done) { drupal_add_js(); $done = true; } ? – Ben Swinburne Aug 7 '13 at 13:44
  • 2
    @Ben exactly :) although if you're adding files, Drupal will only add it once (the js array is keyed by the full path to the file to make absolutely sure of that) – Clive Aug 7 '13 at 13:56

It depends what type of javascript you are adding.

  • drupal_add_js will only add files once, no matter how often it's called ;
  • Settings would overwrite previous values, so it's not a major problem ;
  • Inline code would indeed get added multiple times.

Given that your script needs including only once no matter how often the field is present, I assume you are not generating it's code on the fly - so putting it in a file would be an option.

Otherwise, as suggested by Clive, you could have your own wrapper around drupal_add_js that ensures a given inline js is only added once by using a static variable.

  • This is not strictly true. JavaScript settings don't overwrite previous values in Drupal 7 although it seems they now do in Drupal 8. drupal.org/node/1911578 – Jamie Hollern Sep 3 '14 at 15:47

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.