You are here

function image_lazy_loader_preprocess_field in Image Lazy Loader 8

Implements hook_preprocess_HOOK().

File

./image_lazy_loader.module, line 65
Add Lozad lazy-loading to image / responsive image fields.

Code

function image_lazy_loader_preprocess_field(&$variables) {

  // Provide an extra variable to the field to establish if we should lazy-load
  // this image or not.
  $formatters = [
    'responsive_image',
    'image',
  ];
  if (in_array($variables['element']['#formatter'], $formatters)) {
    $entity = $variables['element']['#object'];
    $view_mode = $variables['element']['#view_mode'];
    $field_name = $variables['element']['#field_name'];

    // Get the field formatter settings.
    $entity_display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
    $field_display = $entity_display
      ->getComponent($field_name);

    // Make the setting available in the field template.
    if (isset($field_display['third_party_settings'], $field_display['third_party_settings']['image_lazy_loader']) && ($is_lazy_loaded = $field_display['third_party_settings']['image_lazy_loader']['lazy_load_responsive_image'])) {
      $variables['#attached']['library'][] = 'image_lazy_loader/lozad';
      foreach ($variables['items'] as &$item) {
        $item['content']['#item_attributes']['lazy'] = TRUE;
        $item['#attributes']['lazy_load_responsive_image'] = $is_lazy_loaded;
      }
    }
  }
}