How to include jQuery Once on your Drupal 8 pages

(as well as the Drupal object, Drupal.settings, and Drupal AJAX)

Much in the same way that jQuery is not included by default on Drupal 8 sites, neither is the very useful jQuery.once() plugin.

To be able to use jQuery Once, just create a library in your theme or module’s libraries file. The library should reference your JS file that uses jQuery Once, and it should list both jQuery and jQuery Once as dependencies coming from core:

js/the-name-of-your-script-that-uses-once.js: {}
- core/jquery
- core/jquery.once

Be wary of including the library on every single page that is styled by your theme as this would have performance implications, particularly if you got into the habit of adding all additional plugins to your global styling library.

To find out more about how to then attach the library to your theme or module’s output only when it is required, have a read of these two very useful links on

  1. Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module
  2. Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme

If you’re looking to replicate the JavaScript options that were available by default in Drupal 7, then you might also be looking for these other dependencies:

- core/jquery
- core/drupal.ajax
- core/drupal
- core/drupalSettings
- core/jquery.once
Like what you read? Give Phil Wolstenholme a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.