0

I have two almost similar websites (one was a test project) and second one is more like final version. On both of them i have quite simple custom module with js and on first web site it works fine, but on the second one - problem is that code in js executs many times (6-10 times), it depends on active modules - i uninstaled some modules and amount of times that js is execute drops down... js file is simple like alert("hi"); and it gets printed like 10 times... i gues that one module couse this issue but i dont know whitch one. maybe someone had such issues? or some advice on how to find out whats wrong.

3

once() may work in many cases. I've also used a flag like:

(function ($, Drupal) {
  let flag = false;

  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      if (flag === false) {
        flag = true;
        console.log('This should only display one time.');
      }
    }
  };

})(jQuery, Drupal);

Please note that I only wrote this in this comment box from memory and didn't actually test this code.

Also FYI, the Drupal.behaviors is correctly running many times, since it is supposed to update every time some kind of state changes that would require it to update (like an AJAX call). So you do have to take extra steps on your side to ensure that certain code only runs once.

  • it helped. however on the test site all js file with bahaviors work normaly without flag... both drupal 8 but older version.... – Forey Vitaliy Oct 4 at 9:24

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.