简体   繁体   中英

JPG vs JPEG2000 vs WebP

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM