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';
  }
}

 

 

Saved you some valuable time?

Buy me a drink 🍺 to keep me motivated to create free content like this!