4

With Drupal 8, I am adding JavaScript to my theme in the libraries.yml so that I can put lift segments into the data layer. But it is running before the body is loaded, and the data layer is being overwritten.

How can I make this script run after the body load?

1 Answer 1

11

Did you use $(document).ready or better Drupal.behaviors?

This is from drupal docs:

When using jQuery it is standard for a large majority of situations to wrap almost all code inside the $(document).ready() function, like this:

$(document).ready(function () {
  // Do some fancy stuff.
});

This ensures that our code will only run after the DOM has loaded and all elements are available. However with Drupal there is an alternate better method; using the functionality of Drupal.behaviors and once(). If used properly this will ensure that your code runs both on normal page loads and when data is loaded by AJAX. The Drupal.behaviors object is itself a property of the Drupal object, and when we want our module/theme to add new jQuery behaviors, the best method is to simply extend this object.

A really basic example:

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    // Using once() to apply the myCustomBehaviour effect when you want to do just run one function.
    $(context).find('input.myCustomBehavior').once('myCustomBehavior').addClass('processed');
    // ... left out the more complex examples
  }
};

Quote from JavaScript API in Drupal 8

0

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.