I wanted to improve performance by reducing file sizes of the images since I am not in control of the uploads.
As the images are used as blocks here is the snippet how I render my image block and how I create the srcset:
<?php
/** @var \Kirby\Cms\Block $block */
use Kirby\Toolkit\Html;
use Kirby\Toolkit\Str;
$alt = $block->alt();
$ratio = $block->ratio()->or('auto');
if ($image = $block->image()->toFile()) {
$srcset = $image->srcset(
[
'480w' => ['width' => 480, 'format' => 'webp', 'quality' => ''],
'850w' => ['width' => 850, 'format' => 'webp'],
'1280w' => ['width' => 1280, 'format' => 'webp'],
]
);
$sizes = '(max-width: 480px) 100vw, (max-width: 850px) 50vw, 33vw';
}
?>
<?php if ($image) : ?>
<figure <?= Html::attr(['data-ratio' => $ratio]) ?>>
<img src="<?= $image->thum(['width' => 1280, 'format' => 'webp'])->url() ?>"
srcset="<?= $srcset ?>"
alt="<?= $alt->esc() ?>">
</figure>
<?php endif ?>
While it works as expected I drastically increased the page load speed. I guess because of a massive amount of preprocessing?!
I was wondering if I could create the files on upload with something like this:
return [
'hooks' => [
'file.create:after' => function ($file) {
if ($file->type() === 'image') {
$sizes = [
['width' => 480, 'format' => 'webp'],
['width' => 768, 'format' => 'webp'],
['width' => 1280, 'format' => 'webp'],
];
foreach ($sizes as $size) {
$file->thumb($size)->save();
}
}
}
]
];
But then I have no clue how to call upon these saved files.
Am I on the right track or is there a better approach to reduce the page load?