Skip to main content

Mise en place de lazyload

Ajouter au projet la librairie LazySizes de AFarkas

yarn add lazysizes

Ajouter dans le fichier JS compilé

'node_modules/picturefill/dist/picturefill.js',
'node_modules/lazysizes/lazysizes.js',
'node_modules/lazysizes/plugins/rias/ls.rias.js',
'node_modules/lazysizes/plugins/object-fit/ls.object-fit.js',
'node_modules/lazysizes/plugins/respimg/ls.respimg.js',

Dans le fichier phtml de l'élément de contenu ayant une ou plusieurs image, ajouter le code ci-dessous (exemple pour une image)

<?
$image = $this->content_element->getMainImage();
$imgQuality = 100;
$imgAction = "imageCrop";


$imageLow = $this->ShowImage(
array(
'image' => $image,
'w' => 10,
'h' => 10,
'action' => $imgAction,
'q' => 10,
'url' => true
)
);


$imageBase64 = $imageLow;
if (file_exists(APPLICATION_ROOT . '/public' . $imageLow)) {
$path = APPLICATION_ROOT . '/public' . $imageLow;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$imageBase64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
}

$sizes = array(
'(max-width: 575px)' => array('w' => 1035, 'h' => 630),
'(max-width: 767px)' => array('w' => 1035, 'h' => 630),
'(max-width: 991px)' => array('w' => 1035, 'h' => 630),
'(max-width: 1199px)' => array('w' => 1035, 'h' => 630),
'(min-width: 1200px)' => array('w' => 1035, 'h' => 630)
); ?>

<? if ($image) : ?>
<div class="wrapper-image">
<picture>
<!--[if IE 9]>
<audio><![endif]-->
<? $imageParams = array(
'image' => $image,
'action' => $imgAction,
'q' => $imgQuality,
'url' => true
);

foreach ($sizes as $kMedia => $size):
$imageParams['w'] = $size['w'];
$imageParams['h'] = $size['h'];
$imageParamsDpr2 = $imageParams;
$imageParamsDpr2['w'] *= 2;
$imageParamsDpr2['h'] *= 2; ?>

<source data-srcset="<?= $this->ShowImage($imageParams); ?> 1x, , <?= $this->ShowImage($imageParamsDpr2); ?> 2x" media="<?= $kMedia; ?>" type="image/webp"/>
<? unset($imageParams['type']);
$imageParams['type'] = 'jp2'; ?>
<source data-srcset="<?= $this->ShowImage($imageParams); ?> 1x, , <?= $this->ShowImage($imageParamsDpr2); ?> 2x" media="<?= $kMedia; ?>" type="image/jp2"/>
<? unset($imageParams['type']); ?>
<source data-srcset="<?= $this->ShowImage($imageParams); ?> 1x, , <?= $this->ShowImage($imageParamsDpr2); ?> 2x" media="<?= $kMedia; ?>" type="<?= $image->getMimeType(); ?>"/>

<? endforeach; ?>

<!--[if IE 9]></audio><![endif]-->

<img src="<?= $imageBase64; ?>" data-sizes="auto" class="lazyload" alt="<?= $image->getName(); ?>"/>
</picture>
</div>
<? endif; ?>