A .libraries.yml file used from a module doesn't tell Drupal to attach the JavaScript and CSS files defined from the library to every page. To understand howattach the library when some conditions are met, a module should implement hook_page_attachments()
.
function mymodule_page_attachments(array &$attachments) {
if (\Drupal::currentUser()->isAuthenticated()) {
$attachments['#attached']['library'][] = 'my_module/lrv';
}
}
Using that code, the library would be attached to correctly defineevery page visited from a logged-in user. Attaching the library to every page, seeeven when they are requested from anonymous users just require implementing a hook similar to the following one.
function mymodule_page_attachments(array &$attachments) {
// Unconditionally attach the mymodule/lrv library.
$attachments['#attached']['library'][] = 'my_module/lrv';
}
The library definition shown in the question contains an error: The dependencies key should not be a sub-key of the js nor the css key, but it should be at the same level of the js and css keys. See how Drupal core defines its librarylibraries, for example the ones defined in core.libraries.yml. (I removed the comment lines from the definitions I copied.)
ThePutting the dependencies key isin the wrong place would not a sub-key of js, nor css, but it is atallow Drupal to load the same level oflibraries from which your library depends. Your library would work only when Drupal already loaded the jscore/jquery and the csscore/drupalSettings keyslibraries for other libraries.
Keep in mind that theThis and not implementing dependencies key defineshook_page_attachments()
are two possible reasons for your library not to work; another reason could be errors in the dependencies ofJavaScript code or in the library from other librariesCSS code (for example a wrong CSS selector).
The hook_page_attachments()
implementations I would rathershown use the following library declarationdefinition.
A .libraries.yml file used from a module doesn't tell Drupal to attach the JavaScript and CSS files defined from the library to every page. To attach the library when some conditions are met, a module should implement hook_page_attachments()
.
function mymodule_page_attachments(array &$attachments) {
if (\Drupal::currentUser()->isAuthenticated()) {
$attachments['#attached']['library'][] = 'my_module/lrv';
}
}
Using that code, the library would be attached to every page visited from a logged-in user. Attaching the library to every page, even when they are requested from anonymous users just require implementing a hook similar to the following one.
function mymodule_page_attachments(array &$attachments) {
// Unconditionally attach the mymodule/lrv library.
$attachments['#attached']['library'][] = 'my_module/lrv';
}