2

Why does this javascript execute 2-4 times per page load:

// mei_library_turn.js
(function ($, Drupal) {
  Drupal.behaviors.mei_library_turn = {
    attach: function() {

      console.log('ready1');

      // There would be a lot more code in here, but I've stripped it all out to debug.

    }
  };

})(jQuery, Drupal, drupalSettings);

That is the entirety of the javascript file. What could possibly be causing this to fire multiple times? The script is not included in the head of the document multiple times.

Most often, when I load the page, it fires 3-4 times. Sometimes just two times.

I realize once() can be used to mask problems like these, but it adds complexity to scripts and I would like to understand what is causing the code to execute multiple times in the first place.

Here is the page where I attach the library:

public function book($marc_num) {

    $output = [];

    $output['something']['#attached']['library'][] = 'mei_library/librarybook';

    return $output;

  }

Here is my libraries file:

librarybook:
  version: 1.x
  js:
    js/mei_library_turn.js: {}
5

Behaviors will be executed on every request, including AJAX requests.

you can use the once function to make sure it is only triggered once.

(function ($, Drupal) {
  Drupal.behaviors.mei_library_turn = {
    attach: function(context, settings) {

       $('main', context).once('mei_library_turn').each(function () {
          console.log('ready1');
       };)


      // There would be a lot more code in here, but I've stripped it all out to debug.

    }
  };

})(jQuery, Drupal, drupalSettings);
| improve this answer | |
  • 3
    For Drupal 8, you need to add a call to $.each() after $.once(): $('main', context).once('mei_library_turn').each(function () {}) – Jaypan Mar 17 at 21:39
  • You're right, I've updated my answer. Thank you. – Rick B Mar 18 at 10:26

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.