Lazyload kirbytag with unknown image height

@Oziris I solved a similar problem months ago for my site.
I used a different approach to avoid calling height()|width() inside my tag because if I understand that correctly the server has to load the image first before it can perform any type of measurement on the file itself.

I ended up using a file.create:after hook to store a few informations in the image file

// Add the relevant meta info
return $file->update([
    'w' => $file->width(),
    'h' => $file->height(),
    'p' => 100 / $file->width() * $file->height(),
]);

In my image kirby tag I the add the new loading attribute since native lazy loading is coming…

$tag->loading  = "lazy";

And finally I add the padding to an extra div container that will hold the actual image

$wrapper = Html::tag('div' , [ $link($image) ], [
    'class' => 'img-wrapper',
    'style' => $tag->file($tag->value) ? "padding-bottom: {$tag->padding}" : NULL,
]);

There are a couple of extra classes involved and some css but that’s stored in the main css file.
I’m happy to share the entire code with you if you’re interested.

1 Like