Attaching libraries

The most common way you'll be libraries is attaching them to your render arrays. This approach implies that the library is needed for the rendering of that component so that if said component is missing from the page, the library assets are no longer included.

Here is what a render array would look like with the previous library we defined attached to it:

return [
'#theme' => 'some_theme_hook',
'#some_variable' => $some_variable,
'#attached' => [
'library' => [
'my_module/my-library',
],
],
];

The #attached property is important here, and it signifies that we are essentially attaching something to the render array, which in our case happens to be a library. In Drupal 7, we could attach CSS and JS files directly, but we now have a standardized libraries API to do so in a more robust way.

However, you may have cases in which the library you need is not linked to a specific render array (a component on the page) but to the entire page itself—all pages or a subset. To attach libraries on an entire page, you can implement hook_page_attachments(). Consider the following example:

function hook_page_attachments(array &$attachments) {
$attachments['#attached']['library'][] = 'my_module/my-library';
}

This hook is called on each page, so you can also attach libraries contextually (for example, if the user has a specific role or something like that). Moreover, there is also the hook_page_attachments_alter() hook that you can use to alter any existing attachments (for example, to remove attachments from the page).

Another way you can attach libraries is inside a preprocess function. We talked about preprocess functions earlier in this chapter; it's simple to achieve:

function my_module_preprocess_theme_hook(&$variables) {
$variables['#attached']['library'][] = 'my_module/my_library';
}

All you have to do is add the #attached key (if it doesn't already exist) to the variables array.

These three methods of attaching libraries are the most common ones you'll encounter and use yourself. However, there are a few other ways and places attachments can be added—you can alter an existing render element definition and you can attach libraries directly in a Twig file. I recommend that you read the Drupal.org documentation (https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module) for more information on these methods.