2

How can I use a custom module to add JS to every page with Drupal 8?

I've found lots of example scattered over the internet that maybe used to work but no longer work.

1 Answer 1

10

Assume the custom module is called example.

First create a example.libraries.yml file in your module root folder like this:

example:
  version: 1
  js:
    example.js: {}
  dependencies:
      - core/jquery

Next in example.module use hook_page_attachments() too add your JS to every page:

/**
 * Implements hook_page_attachments().
 */
function example_page_attachments(array &$attachments) {
  $attachments['#attached']['library'][] = 'example/example';
}

So now the custom module has 4 files:

  • example.module
  • example.info.yml
  • example.js
  • example.libraries.yml

hook_page_build() and hook_page_alter() are now deprecated so can no longer use them.

There is a page drupal.org on adding CSS and JS using a custom module with more information.

5
  • You will also need a example.info.yml file.
    – Decipher
    Apr 13, 2016 at 0:25
  • I am still learning Drupal 8 $attachments['#attached']['library'][] = 'example/example'; shouldn't the first example be the theme name?
    – No Sssweat
    Apr 13, 2016 at 1:10
  • No, this is how to add JS using a custom module, no theme is involved. The module name is repeated as there are no sections in the libraries yml. If however libraries.yml looked like this then you would use example/core.
    – Felix Eve
    Apr 13, 2016 at 5:20
  • @FelixEve thanks for the explanation and posting this Q & A. I will definitely use this in the near future!
    – No Sssweat
    Apr 13, 2016 at 8:14
  • I know its an old post, but realy helped. Thanks @Felix Eve Feb 23, 2018 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.