Our library

In order to get our JavaScript file loaded, it needs to be in a library and attached to something. As you learned in Chapter 4, Theming, the libraries file has the name hello_world.libraries.yml and is located in the root folder of our module:

hello_world_clock: 
  version: 1.x 
  js: 
    js/hello_world_clock.js: {} 
  dependencies: 
    - core/jquery 
    - core/drupal 
    - core/jquery.once  

We only have a single JavaScript file that is needed for our purpose, located in the js directory of our module. But we do have some dependencies. First, we want jQuery loaded because we will use it. Second, we want to have the general Drupal JavaScript library which handles a bunch of things, including behaviors. The last dependency we will talk about soon and it will make a bit more sense then.

Without these dependencies declared, in some cases (especially for anonymous users), Drupal would not have them loaded on the page and our JavaScript functionality would not work.

Now, let's attach this library to our salutation component found inside the HelloWorldSalutation service.

Right after these two lines:

$time = new \DateTime(); 
$render['#target'] = $this->t('world');  

We can add the following:

$render['#attached'] = [ 
  'library' => [ 
    'hello_world/hello_world_clock' 
  ] 
];  

This is nothing new for us but the point is that we are only attaching the library if the component is showing the dynamic salutation message that depends on the time of day. If this message has been overridden, we don't even want to load these libraries, and that is pretty much it. We can dive in and create our hello_world_clock.js file.