Theming

Load JavaScript in Drupal with Drupal.behaviors for Drupal 8, 9, 10, and 11

Last updated
Categories
Up-to-date with minor version
11.0.x

Anyone writing JavaScript for Drupal should use the Drupal.behaviors API when writing their custom JavaScript functionality. Doing so ensures that your JavaScript is executed at the appropriate times during the life cycle of a page, such as when the page loads, or after new DOM elements have been added via an AJAX request.

In this tutorial we'll look at:

  • The problem that Drupal.behaviors solves
  • How to use Drupal.behaviors when writing your JavaScript code

By the end of this tutorial you should be able to explain what the Drupal.behaviors API is, and be able to use it in your own JavaScript.