6

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: {}

1 Answer 1

11

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);
4
  • 4
    For Drupal 8, you need to add a call to $.each() after $.once(): $('main', context).once('mei_library_turn').each(function () {})
    – Jaypan
    Commented Mar 17, 2020 at 21:39
  • You're right, I've updated my answer. Thank you.
    – Rick B
    Commented Mar 18, 2020 at 10:26
  • You need to fix the colon in };) it is throwing error.
    – user31782
    Commented Jul 18, 2022 at 1:02
  • Starting from Drupal 9.2, jQuery.once was deprecated. This change record explains how to use "once()" for versions above 9.2 : drupal.org/node/3158256
    – misterdidi
    Commented Feb 22, 2023 at 10:34

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.