Jul 15, 2019 in Drupal 8, Snippets

Use global theme javascript only in a few occasions. You should make sure javascript is only used on the right places. This snippet shows you how to load javascript when a specific view is loaded only.

use Drupal\views\ViewExecutable;

/**
* Implements hook_views_pre_render().
*/
function MYMODULE_views_pre_render(ViewExecutable $view) {
  if (isset($view) && ($view->storage->id() == 'MYVIEWID')) {
    $view->element['#attached']['library'][] = 'MYMODULE/MYLIBRARY';
  }
}