-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeme.theme
45 lines (38 loc) · 1.66 KB
/
theme.theme
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?php
/**
* Implements template_preprocess_responsive_image().
*/
function theme_preprocess_responsive_image(&$variables) {
_lazyload_picture_alter($variables);
}
/**
* Generates an LQIP and alters picture markup with attributes needed for lazy loading functionality.
* @param $variables
* @param string $lqip - image style id used for LQIP generation.
* @param array $skip - array of responsive image ids that do not require lazy load alterations.
*/
function _lazyload_picture_alter(&$variables, $lqip = 'lqip', $skip = NULL) {
// Skip lazyload alterations for defined responsive image ids.
if ($skip) {
$variables['skipped'] = TRUE;
if (in_array($variables['responsive_image_style_id'], $skip)) return;
}
$variables['skipped'] = FALSE;
// Generate a LQIP image.
$image_style = \Drupal::entityTypeManager()->getStorage('image_style')->load($lqip);
$variables['lqip'] = $image_style->buildUrl($variables['uri']);
// Integrate lazy loading for all responsive image entities.
// Replace src with data-src attribute.
$variables['img_element']['#attributes']['data-src'] = $variables['img_element']['#uri'];
$variables['img_element']['#attributes']['class'] = 'lazyload';
unset($variables['img_element']['#uri']);
// Also replace srcset with data-srcset attributes.
foreach ($variables['sources'] as $source) {
$storage = $source->storage();
$srcset_value = $storage['srcset']->value();
$source->removeAttribute('srcset');
$source->setAttribute('data-srcset', $srcset_value);
}
// Call lazysizes library.
$variables['#attached']['library'][] = 'nioweb/lazysizes';
}