Images often account for most of the downloaded bytes on a web page and often occupy a significant amount of visual space. As a result, optimizing images can frequently yield some of the largest byte savings and performance improvements for your website. The fewer bytes the browser has to download, the less time the user will have to wait for the render of useful content on the screen.
Image optimization is both a science and an art. It is a science because there are many well developed techniques and algorithms that can significantly reduce the size of an image. It is an art because there is no one definitive answer.
But how we can optimize our images from mobile form in addition to using image magic or any other web optimization tool?
The img element
The HTML5 <img> element has been designed to give the developer the ability to optimize the images according to the screen resolution. This is done through two attributes,
sizes. With a very simple syntax, you can instruct the browser to decide which one of the different image sizes are needed:
alt="The Death Star">
The browser, in this case, will choose the image best suited to its resolution. But, the assumption is that the image should be displayed in full screen (100vw). That’s usually not an awful assumption to make.
sizes attribute is used to avoid this problem and, therefore, to help the browser choose the most optimized image for that case. You can use sizes to match your CSS layout exactly and tell the browser exactly how big that image is going to be on every screen size, matching how your breakpoints work in your design.
That can get a little complicated, and honestly it might be a little dangerous. You’re putting CSS stuff in markup and you know how that goes. It can be automated or injected server-side. Even in this case the syntax is really very simple: