How do I add a Javascript library to a field formatter? I'm trying to include a Javascript gallery (jQuery lightGallery) on my new Drupal 8 site and wrote a field formatter for this purpose. 

Now I need to add the jQuery lightGallery to pages using this field formatter and call the library when the page is ready. I am confused about how I am supposed to do this, though. 

I defined the library in the module containing my field formatter, but I'm not sure how I attach it only on sites that contain the field. 

The documentation of the library uses the jQuery $(document).ready function to call the libary, how would that work inside a Drupal module?
In your formatter's viewElements

public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta =&gt; $item) {
  $elements[$delta] = array(
    '#theme' =&gt; 'theme_name_if_any',
    '#variablenametobepassed' =&gt; $this-&gt;viewValue($item) * 20, // any other preprocessing
    '#attached' =&gt; array('library'=&gt; array('module_name/library_name')),
  );
}

return $elements;
}