I am trying to load content via AJAX calls which may include Javascript and its settings. This works more or less, but I cannot make sure whether a certain javascript code has been inserted and executed before. Now I need to find out, whether in case of problems resulting from a modules javascript code being executed multiple times, I would need to fix the modules javascript or whether I would have to take other precautions.

My question: Given Drupal's coding standards for Javascript added by modules, should it be unproblematic to execute it multiple times? I am aware of some modules where the javascript part is badly coded and problems will result, I just want to know whether this is allowed by some Drupal javascript standards (if any exist)

2 Answers 2


When you rely on Drupal's ajax framework, then it will take care of automatically adding only those js files on ajax requests that have not been added before. To accomplish that, it submits all currently existing js files to the server on each ajax request.

  • Just to make sure, I am not missing anything, you are referring to the D7 framework ( api.drupal.org/api/drupal/includes%21ajax.inc/7 ), correct? In anyway it answers my question in so far that I should implement some logic or precautions. I hoped to avoid sending to much info with every AJAX request.
    – Martin
    Commented Jun 22, 2012 at 20:38
  • Sorry, I missed the 6 tag, yes my answer relates to Drupal 7.
    – Berdir
    Commented Jun 22, 2012 at 20:55

Usually, you add javascript with Drupal's behaviors as explain in the doc. If you have AJAX callbaks, javascript behaviors will be reloaded and this can cause some trouble.

For exemple, on my website I added moving clouds in the header with a javascript behavior, the speed beeing added by increments, each time I loaded an AJAX form it was sped up unintentionally. I could either add a jQuery Once behavior or use the common $(document).ready function.

So in conclusion, it depends on the way you call the code inside your javascript file. Your javascript code called inside a $(document).ready function should be loadded once, even with AJAX callbacks. On the contrary, a Drupal javascript behavior will be executed each time your DOM is updated, exept with jQuery Once enabled:

Drupal.behaviors.mybehavior = {
  attach: function (context, settings) {
    $('input.mybehavior', context).once('mybehavior', function () {
      // Apply the MyBehaviour effect to the elements only once.

Now if you are concerned with others javascript coding standards, see the official Javascript coding standards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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