Drupal behaviors

One of the most important things you need to know when writing JavaScript files in Drupal is the concept of behaviors. But in order to understand that, let's get a bit of context.

When writing JavaScript code using jQuery, it's often standard to wrap our code inside a ready() method statement as follows:

$(document).ready(function () {
  // Essentially the entirety of your javscript code.
});

This ensures that your code runs only after the entire DOM has been loaded by the browser. Moreover, the use of jQuery for this helps a great deal with cross-browser compatibility and also allows us to place this code wherever we want on the page (header or footer).

In Drupal, however, we have a different solution which is better in the ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.