1

I used the following code.

libraries.yml

    my_module.admin:
  version: VERSION
  js:
    js/my-module.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

my_module.module

 /**
 * Implements hook_page_attachments().
 */
function my_module_page_attachments_alter(array &$attachments) {

$attachments['#attached']['library'][] = 'js/my_module';
  // $attachments['#attached']['library'][] = array('my_module', 'admin');
}

my_module/js/my_module.js

(function($, Drupal, drupalSettings) {
    Drupal.behaviors.my_module = {
      attach: function(context, settings) {
        $(document).ready(function() {
            alert("hello");
            console.log('Loaded');
          }
        };
      })(jQuery, Drupal, drupalSettings);

I have tried many other changes, but the JavaScript file is not used.

I have ported Drupal 7 code that implements hook_boot() and includes that JavaScript file, to Drupal 8.

2

See Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme. In your case, the library name is wrong. The right format for the name is module_name/libraries_name.

/**
 * Implements hook_page_attachments().
 */
function my_module_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'my_module/my_module.admin';
}
0

Following changes worked for me :

$attachments['#attached']['library'][] = 'my_module/my_module.admin';

and

my_module.admin:
  version: VERSION
  js:
    js/my_module.js: {}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

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.