Use of modern graphic formats in web projects

Eddie Osmani, in the article “The Price of JavaScript in 2018 ”, voiced one valuable idea: the time required to process a script of 200 KB in size and to process an image having the same size varies significantly. The fact is that when processing the code, the browser needs to do more extensive work than in preparing for the use of images. Here's what the article says about it:

A JPEG image needs to be decoded, rasterized and displayed. And the JS bundle is necessary, if we consider it simplistically, load, parse, compile, execute. In fact, the engine has to solve other problems in the process of processing JS-code. In general, it should be borne in mind that much more system resources are spent on processing JavaScript code, the size of which, in bytes, is comparable to the size of other materials.

These words were written in 2018, but they are still more than fair. True, given the current situation, the idea expressed here is perceived today a little differently.



Considering that a pandemic has erupted in the world now, I noticed that my Internet connection has become unstable. Fortunately, due to the fact that the Internet is protected by excellent specialists who do not know fatigue, most of the World Wide Web still works fine. But on the Internet, something is definitely happening. I use a 100 Mbps connection, but I get the feeling that I'm sitting on a 3G modem.

This makes some changes to the above reasoning. The fact is that our devices can parse and compile JavaScript at the same speed that they could do it a couple of weeks ago. But data now travels through networks more slowly. As a result, at the moment it is extremely important how much data representing a certain resource is transmitted over the network when this resource is loaded.

And sites usually have much more than 200 KB of images. A page with several megabytes of pictures is usually the case. Many developers (and me too!), As a rule, do not think at all about the size of media materials.

But, which is very good, optimizing the images used on web pages is not so difficult. In this article we will talk about how to use modern graphic formats like WebP. Images saved in such formats often turn out to be 2-3 times smaller than those for which the old and well-known old formats (like JPG and PNG) are used by everyone. The use of new formats can seriously change the situation for the better.

General overview of modern graphic formats


To improve the work with web graphics, we can use the following three formats:

  • JPEG 2000 is a format that is an improved version of regular JPG. This format was developed in 1997, primarily for use in cinema and in medicine. It allows you to compress images stronger than JPEG, but with fewer artifacts.
  • JPEG XR is a format related to JPEG 2000. It was developed by Microsoft in 2009.
  • WebP is a format Google created in 2010 for the web. The main goal of its development was to use advanced methods for optimizing images in order to reduce file sizes. WebP supports transparency and even animation.

Here we will mainly talk about WebP. Formats related to JPEG, we will discuss where the issue of browser compatibility will be raised.

How much can you win using alternative graphic formats?


A few months ago, I used the following image in one material.


The image used in one material

I conducted some experiments, considering the use of the JPG and PNG formats for storing the original image. I optimized image options using imagemin in order to find out what WebP can give me instead of these “retro” formats.

The results were incredible.
Image FeaturesOriginalWebp
.Png file (from Photoshop)742 Kb61 Kb! (92% less)
Optimized .png file (after Imagemin)178 Kb58 Kb! (67% less)
File in .jpg format (from Photoshop)242 Kb50 Kb! (79% less)
Optimized file in .jpg format (after imagemin)151 Kb50 Kb! (67% less)

I conducted similar experiments with many images. It almost always turned out that WebP files were 30-70% smaller than even optimized versions of graphic files of other formats.

This may raise the question of how conversion to WebP can affect SVG images. I did not conduct such experiments with SVG. SVG is a vector format. This means that the images in it are built on the basis of mathematical instructions, and not on the basis of information about the color of individual pixels. Converting an SVG image to WebP means giving up the ability to scale SVG images, which, I believe, is unacceptable. In addition, I suspect that such a conversion, in most cases, will lead to an increase in file sizes.

Browser compatibility


To learn about how certain graphic formats are supported by browsers, take a look at caniuse.com .

WebP format is supported by most browsers.


Support for WebP format by browsers

Although the level of support for this format is very high, it’s very bad that Safari and Internet Explorer do not support it.

And here is information about JPEG 2000 support.


Support for JPEG 2000 format by browsers

So, now Safari is on our side, but Internet Explorer is again out of work.

What about JPEG XR?


Support for JPEG XR format by browsers

And here Internet Explorer was distinguished. As a result, using these three formats, we override all existing browsers (KaiOS Browser does not support any of these formats, and I apologize to him for ignoring him, but I don’t even know what browser it is )

Now let's talk about how to choose different image formats designed for different browsers.

The picture element to the rescue


HTML has two elements for outputting images. The first can be compared to an international pop star like Madonna. It is img. And the second is like a new band, known only in narrow circles of music lovers. This is an element picture.

The element pictureappeared in HTML much later than img. The main goal of this new element is to allow developers to download various graphic resources depending on the screen resolution, or depending on whether the browser supports a certain graphic format.

Here's what the HTML code that uses the element looks like picture:

<picture>
  <source srcset="/images/cereal-box.webp" type="image/webp" />
  <source srcset="/images/cereal-box.jp2" type="image/jp2" />
  <img src="/images/cereal-box.jxr" type="image/vnd.ms-photo" />
</picture>

An element picturemay include many child elements sourceand one element img. The browser sequentially parses these elements, selecting, based on the attribute type(s media), one of them that can use it. When such an element is found, the browser finds out the address of the image using the attribute srcset, and then displays this image using the element img.

The attribute srcsethas much greater capabilities than the usual one src, but, fortunately, we can consider it as an analogue src. In general, elements sourceare something like settings that correspond to different images. The imgimage that best matches the environment in which the page is viewed is included.

In Chrome, for example, after processing the above markup, the browser will come to something more or less equivalent to the following code:

<picture>
  <img src="/images/cereal-box.webp" />
</picture>

Using a set of consecutive elements sourcemeans that at least one of them will be suitable in each browser. So, most browsers use a webp image, Safari will load a jp2 image, IE a jxr image.

It is appropriate to recall that Internet Explorer does not support the element picture. This item is too new for this browser. But, despite this, the above markup fragment in IE will work as expected.

The fact is that when the browser stumbles upon an element unknown to it, it considers it as an element div. As a result, when parsing our code, IE sees many elements div, as well as one tag<img>which contains the path to the jxr image. And this, as it turns out, is the very format that Internet Explorer supports.

Simplified alternative


The above code fragment is extremely good because it allows you to use modern graphic formats in all current browsers. But the use of such code is based on the assumption of the existence of those images to which it has links.

If you create such images yourself - you have to invest a lot of manual labor in it. If you generate them automatically, this can significantly increase the build time of the project. Graphics processing, as you know, becomes a very slow process when it comes to a lot of images.

Only very few visitors to my blog use Internet Explorer (in the last 7 days only 3 people with IE tried to view it, which amounted to 0.02% of the traffic). Therefore, I decided to use a simplified version of the above solution:

<picture>
  <source srcset="/images/cereal-box.webp" />
  <img src="/images/cereal-box.jpg" />
</picture>

I give a compact webp image to those browsers that support this format (Chrome, Firefox, Edge), and to browsers that don't support this format (IE, Safari), I offer a legacy of the past - a jpeg image.

From my point of view, this is an example of progressive improvement. The project remains operational on older browsers, although loading images takes longer. This is a compromise that suits me. (True, I hope that WebP support will appear soon in Apple’s browsers as well).

Verification of the solution


Developer tools will always assume that the image contains what was originally written to the srctag attribute img. If you check the item using the tab Elements, you can see that the page is using a jpg image.

In order to check the operability of all this, it is best, as it seems to me, to right-click on the picture and select the item In Chrome when the command is executed, the system should offer to save the file with the extension .webp. But in Safari it will be a jpeg file.

In order to find out exactly which graphic file was received from the server when the page was loaded, you can refer to the developer toolbar Network.

Convert image files to WebP format


Google has created a set of tools aimed at working with webp-files. One such tool is called cwebp . It allows you to convert graphic files of other formats to WebP.

If you are using MacOS, you can install this toolkit using Homebrew:

brew install webp

On other platforms, I believe it will be necessary to download the appropriate libwebp package from the repository.

After installing the tools, you can use them like this:

cwebp -q 80 cereal.png -o cereal.webp

Consider this command:

  • The flag -q 80allows you to set the image quality. Its value varies from 1 (worst quality) to 100 (best). You can experiment with different values. I found out that it is best to ask something in the region of 70-80.
  • The file name cereal.jpgis the original image that needs to be converted to webp.
  • The construction -o cereal.webpsets the path to the output file.

No one wants to waste time typing such commands manually. Fortunately, this task can be automated.

Using modern image formats in React applications


A component is a great way to ignore some of the element's oddities <picture>. I use React components for this. In my opinion, it is very convenient. Here's what it looks like:

const ImgWithFallback = ({
  src,
  fallback,
  type = 'image/webp',
  ...delegated
}) => {
  return (
    <picture>
      <source srcSet={src} type={type} />
      <img src={fallback} {...delegated} />
    </picture>
  );
};

Using the component is ImgWithFallbackvery similar to working with a regular tag img:

<ImgWithFallback
  src="/images/cereal.webp"
  fallback="/images/cereal.png"
  alt="A photo showing the expiration date on a box of Lucky Charms"
/>

The use of modern graphic formats with stylized components


If you use libraries styled-componentsor emotionyou may be used to special image design:

const FancyImg = styled.img`
  whatever: stuff;
`

The very good thing is that it works with our component ImgWithFallback. You can wrap it in the appropriate wrapper just like any other component:

const FancyImg = styled(ImgWithFallback)`
  whatever: stuff;
`

The reason for the operability of this design is how the auxiliary structure works exactly styled. It generates a class and embeds it in the document stylesheet. Then the name of the generated class is passed to the component as a property:

<ImgWithFallback className="sc-some-generated-thing" />

We delegate all the properties to the child tag <img>, as a result, the correct styles are applied to the image, as it usually happens. Everything works exactly as you might expect.

Using the gatsby-image Package


If you are using Gatsby, then be aware that the package gatsby-image, when used normally, already uses many image optimizations. This includes converting images to webp format (although, for this you need to enable the appropriate option).

The package gatsby-imagedoes not claim to be a replacement img. Its use may not be so simple, its internal mechanisms can lead to surprises that make life difficult for the developer.

If you are interested in this package, take a look at its documentation .

Cons of WebP


The only real drawback of webp that I managed to find is that it is very inconvenient to work with files of this format.

Most desktop image packages do not yet support it. For example, I cannot open webp files in Preview on MacOS. This means, let's say that if I save a webp image from a web page, I will not be able to view it on my computer!

Converting webp files to jpeg files is a fairly simple process. On the Internet you can find many free services that perform such a conversion. But, again, this is not as convenient as working with traditional graphic formats. If your site offers users to download graphic files from it, you may decide that you do not need to switch to webp.

Summary


I really like the fact that using webp I was able to reduce the size of the images on my blog by about 50%. In addition to the fact that in our difficult times this improves the user experience of working with him, I also hope that this will allow me to save a little on paying for traffic.

Of course, the idea of ​​manually converting image files to webp format seems quite impractical. I am already studying the question of how to automatically convert jpg and png files to this format. Ideally, this process should occur completely unnoticed by the developer, during the assembly of the site.

The creators of web projects are usually not particularly interested in the features of using new image formats. But I believe that understanding this issue is very useful. After all, using WebP is probably the easiest way to reduce the size of your web project by hundreds of kilobytes.

Dear readers! Do you use the WebP format?


All Articles