I have created a custom module, which is working. Except the JavaScript, which is not being detected. I have been following the description at https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview and I have checked other modules.

What have I done to implement JavaScript? I have created a file with the following JavaScript content (location: MODULE-ROOT/js/info.js):

 * @file
 * Info behaviors on node edit form.

(function ($, window) {

  'use strict';

  Drupal.behaviors.nodeEditForm = {
    attach: function () {
      console.log('Hi there!');

})(jQuery, window);

Then I have added the following content into my MODULE-NAME.libraries.yml file:

  version: 'VERSION'
    js/info.js: {}

I expect to see "Hi there!" in my webdeveloper tools inside Google Chrome browser, after I flush the entire Drupal 8 and browser cache. I do not get any output there.

Is it a "must" to attach the JavaScript to any existing behavior? If so: how can I learn which behavior is tied to an node edit form?

Thanks for your attention.

  • But did you load the library in code anywhere? It must be attached to be included in the page. In this example it sounds like you'd want to do a hook_form_alter, and attach your library ex: $form['#attached']['library'][] = 'mymodule/nodeEditForm';
    – Kevin
    Commented Sep 6, 2017 at 20:21

1 Answer 1


Drupal uses a high-level principle: assets (CSS or JS) are still only loaded if you tell Drupal it should load them. Drupal does not load all assets (CSS/JS) on all pages, because this is bad for front-end performance.

You need to inform Drupal to attach your library to the page.

In your case, you can use hook_form_alter and check the $form_id or hook_form_FORM_ID_alter for a single case and add this:

$form['#attached']['library'][] = 'mymodule/nodeEditForm';

Then clear the cache. Search the core folder for $form['#attached'] for more examples. You should then see your js file listed in the source of the page as well as console log output.

  • Thanks that worked. Is there also an "object oriented" way to add the library from a controller or service? I have not found anything about that in the Drupal.org documentation at drupal.org/docs/8/creating-custom-modules/…
    – jepster
    Commented Sep 6, 2017 at 21:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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