JPG vs JPEG2000 vs WebP
Asked Answered
M

1

15

I'm building my website using React and have multiple images to display. After running an audit using the Google Chrome audit function, I've been getting the "Serve images in next-gen formats" opportunity message.

After reading about the various formats (WebP, JPEG2000, JPEGXR), it seems each is supported on only select browsers. For instance, I can't just convert all of my images to WebP because they won't show up on the Safari browser. So my issue is how to I "serve" each type of image depending on the browser being used? This is what I've tried:

I have 3 types of files, jpg, JPEG2000, and WebP. Each is being imported like:

import Imagejpg from './path/image.jpg'
import ImageJPEG2000 from './path/image.JPEG2000'
import ImageWebP from './path/image.webp'

Then in my class, I have an object array that contains the images. To use the images:

 <picture>
      <source>
          srcSet={`
            ${project.Imagejpg},
            ${project.ImageJPEG2000},
            ${project.ImageWebP},
      </source>
     <img src={project.imageWebP} alt=""/>
 </picture>

Now, if I only use the jpg image, it works fine on all browsers as most browsers can use jpg. But I'm trying to optimize my site and use the better types of image files. Is there a way to use the several types of files or is there something I am missing?

Mazdaism answered 21/12, 2018 at 20:16 Comment(2)
Personally, I think the overhead of serving 3 different files negates any optimization a better format might provide. Stick with jpg until there is better support.Tonatonal
Sticking with jpg is definitely the easier way to go. I wasn't excited about importing 3 types of files and I was starting to question if I was actually optimizing. Thanks for the input!Mazdaism
L
8

The solution is indeed in the <picture> element, but using multiple sources.

The code with correct syntax looks like this:

<picture>
    <source srcSet={project.ImageWebP} type="image/webp" />
    <source srcSet={project.ImageJPEG2000} type="image/jp2" />
    <source srcSet={project.Imagejpg} type="image/jpeg" />
    <img src={project.Imagejpg} alt="" />
</picture>

Explanation

Seeing the picture element, a browser will download the first source it can support. If it's an old browser that doesn't support <picture> at all, it will fall back to the <img /> tag which has a jpeg source.

This is a quick and easy win to improve your page's speed. The tiny overhead in extra HTML bytes does not negate the speed improvements except in extreme scenarios, like very small and simple images.

Lunch answered 22/8, 2019 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.