Theming

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

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.