Best approach to hero images

Hi all

I am trying to figure out a practical way to load/resize hero images. I would like to be able to load images through the panel and have them resized automatically. (However, I don’t even know if I need this I’m just thinking it would be a cool feature. So if this is not practical please tell me.)

I currently have hero images (both mobile and desktop) loaded through the CSS file and I also built the functionality to load them through the panel. When I load them through the panel, I resize them for both desktop and mobile and then load them through inline CSS. I am not sure how good this method is though. It seems that there will be a lot of resizing going on in the background. Am I correct?

Should I just stick to manually resizing the images and loading them through CSS, or is there a better panel approach?

The files are only resized once, so I don’t see a problem here. In an ideal world, you would not upload images that are huge (to save resources).

And yes, you have to inline CSS, there is no other useful way.

What I don’t understand is when you resize them, via a hook at upload?

Thanks Sonja.

I have this code within the head.

  <?php if($heroImage = $page->cover()->toFile()->thumb(['width' => 2560, 'quality' => 80, 'format' => 'webp'])): ?>
  <style>
    .hero {background-image: url(<?= $heroImage->url() ?>)}
  </style>
  <?php endif ?>

Also, not sure if this is the right use of ‘thumb’ as it’s not really a thumbnail.

Well, that’s what the method is called and that’s perfectly ok.

What is not ok, is that you miss out on checking if you have a file object before calling thumb(), without that, if the file does not exist, PHP will throw an error.

Oh I already check if the file object is there, I just didn’t copy it here.

So with this method, the file will be resized only once, not every time page is loaded?

It’s also possible to load the File using a relative absolute approach, putting e.g. picture element into the background with object cover.

I often find myself getting pagespeed penalty when using background images (at LCP or above the fold)

where both background image and object cover image could both be futher optimized with lazyloading srcset and whatsoever.

1 Like

Thank you, I’ll keep playing around. I’ll see how many hero images there will be. It could be simpler just doing it manually.