Whether you're trying to add your own JavaScript to a page, or make use of one of the many popular libraries provided by Drupal core, it's important to understand the asset library system when working with JavaScript in Drupal. By wrapping your JavaScript in an asset library it can be added to every page, selectively included when it's needed, or be easily modified by others.

In addition to the inclusion of third party libraries, Drupal core also contains numerous Drupal-specific JavaScript libraries that make it easier to do things like implement AJAX calls to a Drupal route, localize UI strings, and pass configuration stored in the database to the front-end. Drupal also contains several external projects in core like jQuery (but some components have been removed), Backbone, Underscore (removed in Drupal 10), and Modernizer (deprecated in Drupal 10; will be removed in Drupal 11).

Example tasks

  • Add custom JavaScript to a site
  • Utilize the JavaScript libraries that are included in Drupal core
  • Customize how JavaScript is loaded on a site to minimize the overall page size

Confidence

The asset library concept and associated methods are stable in Drupal. JavaScript library dependencies in Drupal core are the most likely to change or be removed (either partially or wholly). For example, here is a list of changes related to jquery in Drupal core. The Underscore.js library was removed in Drupal 10 and Modernizr has been deprecated in Drupal 10 and will be removed in Drupal 11.

Drupalize.Me resources

Topic
Tutorial
Tutorial
Tutorial
Tutorial

Integrating JavaScript with Drupal

Tutorial
Tutorial
Tutorial
Tutorial
Tutorial
Tutorial
Tutorial

Using Ajax in Forms

Tutorial
Tutorial
Tutorial

JavaScript libraries in core

Tutorial
Tutorial
Tutorial

More Guides

We have guides on many Drupal skills and topics.

Explore guides

External resources

Changes

  • [9.5.0/10.0.0] Added a new 'add_js' Ajax command (Drupal.org)
    • Ajax commands can now return a promise to ensure that the command is complete before executing the next Ajax command in the queue.
    • The Drupal.Ajax.prototype.success method now returns a promise, if your code overrides this method, make sure to return a promise.