Some of my Drupal behaviors are firing multiple times while as a logged-in user:

(function myFunction (Drupal) {
  "use strict";
  Drupal.behaviors.myBehavior = {
    attach: function attach (context) {

      console.log("Hello world");

The above will log "Hello world" multiple times in console while logged in, only once while logged out.

I've been working through updating scripts to use Drupal's once() library, but am unsure if this is the fix or just a patch.

Is there a higher context I could look at that might be causing this? I'm unsure of the difference between logged-in and logged-out here.


1 Answer 1


Drupal.behaviors does not only fire on page load, it fires on ajax calls or whenever new elements are inserted into the DOM. The once library is built to handle this - you attach handlers to only fire a single time.

You can read more about using once here: https://www.drupal.org/docs/drupal-apis/javascript-api/javascript-api-overview

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.