Speeding Up Page Load and Reducing the Amount of Time it Takes Using Responsive Images

Since there are many variables to take into account, including the image size, placement, display area, and user’s internet speed, it can be difficult to ensure that images appear visually appealing on all types of screens. Most often, programmers use …


This content originally appeared on DEV Community and was authored by Fatemeh Paghar

Since there are many variables to take into account, including the image size, placement, display area, and user's internet speed, it can be difficult to ensure that images appear visually appealing on all types of screens. Most often, programmers use the same image for all screen sizes and let the browser resize it to fit the available space. This is not advised, though, as the browser will continue to download the full-size image even if it is displayed at a smaller size, wasting user bandwidth and increasing the time it takes for a page to load, especially on slower internet connections.

In order to address this issue, responsive images, which are images optimized for the user's screen size and device, can be used. This means that the image will be downloaded at the correct size and quality, reducing the amount of data transferred to the user and speeding up page loading times. There are several approaches to implementing responsive images, and this article will provide a thorough overview of these approaches.

img srcset Attribute

The simplest approach to implement responsive images is by using the "srcset" attribute on the "img" tag. This attribute enables developers to specify multiple images of different sizes, and the browser will then automatically choose the most suitable image for the user's screen size.

<img
  src="tree-1200.jpg"
  alt="A tree"
  srcset="tree-400.jpg 400w, tree-800.jpg 800w, tree-1200.jpg 1200w"
/>

Allow me to clarify this code for you. Firstly, there are two regular attributes, "src" and "alt", that are used with all images. In the unlikely event that the user's browser does not support "srcset", the "src" URL will be used instead. However, "srcset" has been supported by all major browsers for at least 5-10 years, so this is rarely an issue.

The "srcset" attribute is where it becomes a bit confusing. It takes a comma-separated list of image URLs and their corresponding widths. For example, the first item in the list "tree-400.jpg 400w" has the URL "tree-400.jpg". The URL name doesn't matter, but it's useful to name multiple images of the same image with the size in the name.

The second part of this item, "400w", may be confusing."w" doesn't refer to a CSS unit; instead, it represents the intrinsic width of the image in pixels. This is the actual width of the image file, which you can find by inspecting the image in your file browser/explorer. For instance, on a Windows machine, right-click the image and select "Properties", while on a Mac, look for "Get Info". In this case, the image is 400 pixels wide, so we set the width to "400w".

The browser will then utilize this information to determine the best image to download. For example, if the user's screen is less than 400px wide, the "tree-400.jpg" image will be used since it's the smallest image that can be used without pixel stretching or blurring. When the browser width exceeds 400px, it will switch to the "tree-800.jpg" image. This continues until the browser reaches the largest image in the list.

The browser now downloads a smaller image for small screens, while large screens continue to receive high-resolution images, which is a significant improvement. This significantly reduces the amount of data transferred to the user, which leads to quicker page loads. An illustration of this code is provided below. To see the smaller image being downloaded, try scaling down your browser and refreshing the page.

<img
  style="width: 100%; border-radius: 1rem;"
  src="https://placehold.co/3200x800/png"
  srcset="
    https://placehold.co/800x200/png   800w,
    https://placehold.co/1600x400/png 1600w,
    https://placehold.co/3200x800/png 3200w
  "
/>

Image description

During testing, you might have observed that the downloaded image was larger than anticipated. For instance, if your screen width was 700px, the browser may have downloaded the 1600px wide image rather than the 800px wide image. This is because the browser considers the pixel density of your screen. On a high-resolution device or when you have a high zoom level on your browser, the browser will download a larger image to ensure it appears crisp on your screen, since each CSS pixel corresponds to multiple pixels on your screen. To verify your device's pixel density, you can use the window.devicePixelRatio command in the console.

Handling Different Pixel Densities: Here’s How!

In some cases, you may have the same size image on your screen, but you want to make sure it looks good on high resolution devices as well. For example, if you have a logo that is consistently 100px wide, providing only 100px wide images may make the logo look blurry on high resolution devices. To resolve this issue, use the srcset attribute to specify the pixel density using x units and provide multiple images of different sizes.

<img
  src="logo-200.jpg"
  alt="Our Logo"
  srcset="logo-100.jpg 1x, logo-150.jpg 1.5x, logo-200.jpg 2x"
/>

The code shown above is similar to the previous example that uses the srcset attribute. However, instead of using hard-coded pixel values, it uses units such as 1.5x and 2x, which correspond to the pixel density of the screen. This means that if a user's screen has a pixel density of 1.25 device pixels per CSS pixel, the image with the smallest size that can be used without stretching or blurring pixels will be selected, which in this case is the logo-150.jpg image.

You don't need to include the 1x unit as that is the default. If you only have 2 images you can use logo-100.jpg, logo-200.jpg 2x instead of logo-100.jpg 1x, logo-200.jpg 2x.

img sizes Attribute

mages. However, there are instances where the image size doesn't match the screen width. This blog is a good example of that since on small screens, the content takes up the full-screen width, but on larger screens, the content is centered with a limited maximum width. If we solely use srcset, the images would scale based on the full browser window, which would result in images being bigger than required on large screens. This is where the sizes attribute comes into play.

The sizes attribute allows you to specify a single size for your image, such as 50vw, or a list of media queries that determine the size of your image. If you don't include the sizes attribute in your img, it automatically assumes a size of 100vw, which is why the images above scaled off the full browser window. Let's see how we can use the sizes attribute to take into account a blog like this with a maximum size.

<img
  src="tree-1200.jpg"
  alt="A tree"
  srcset="tree-400.jpg 400w, tree-800.jpg 800w, tree-1200.jpg 1200w"
  sizes="(max-width: 800px) 100vw, 800px"
/>

The previous code is unchanged except for the addition of the sizes attribute. This attribute accepts a comma separated list of media queries and sizes. A list item can be divided into two parts: media queries and sizes. A media query specifies a condition that should be checked. For example, size specifies the size of the image to use when the screen width is less than 800 pixels and the condition is true.

The first item in the list, ("max-width: 800px) 100vw", checks if the screen width is less than 800px and specifies that the image should take up the full width of the browser window. The second item, "800px", does not have a media query and serves as the fallback size. It specifies that the image should be assumed to take up 800px on the screen, and this size is used if none of the previous media queries are true.

By combining these two items, the code ensures that the image size is chosen based on the browser width up to 800px. Beyond 800px, the image will never take up more than 800px on the screen, so the size is determined based on that limit. This approach is suitable for blogs like this one, where the content is centered on the page with a limited maximum width at larger screen sizes.

<img
  style="width: 100%; border-radius: 1rem;"
  src="https://placehold.co/3200x800/png"
  srcset="
    https://placehold.co/400x100/png   400w,
    https://placehold.co/800x200/png   800w,
    https://placehold.co/1200x300/png 1200w,
    https://placehold.co/1600x400/png 1600w,
    https://placehold.co/3200x800/png 3200w
  "
  sizes="(max-width: 800px) 100vw, 800px"
/>

Image description

To show how different pixel densities impact the selection of the image, the author included a variety of image sizes in the example code. The browser might download a bigger image than the one you requested on high-resolution devices. If the user zooms in on the image, this might also take place.

Possible Errors and Pitfalls

Despite being a powerful attribute, the sizes attribute has some potential pitfalls that need to be considered.

The Order Is Significant!

The order of media queries in the sizes attribute matters because the browser selects the image based on the first media query that is true.

<img
  src="https://placehold.co/3200x800/png"
  srcset="
    https://placehold.co/400x100/png 400w,
    https://placehold.co/800x200/png 800w
  "
  sizes="(max-width: 800px) 100vw, (max-width: 500px) 50vw, 1200px"
/>

The order of the media queries in the sizes attribute is important because the browser chooses the first media query that is true. If you write your media queries in the order presented in the previous example, the first media query (max-width: 800px) will always be true for screen sizes less than 800px, so the second media query (max-width: 500px) will never be used. To avoid this problem, you should order your media queries from the most specific to the least specific.

It is crucial to ensure that the default size, which has no media query, comes last in the sizes attribute. This is because it always evaluates to true, and if it appears first, it will be selected over any other media query.

How to Use Percentages

While exact measurements like pixels and responsive measurements like viewport width (vw) are supported, percentage sizes like 50% are not. The browser cannot determine the width of a percentage-defined element until it knows the width of its parent element. This would require the browser to for the entire page to load before deciding which image to download, resulting in a subpar user experience.

The picture Element

Up until this point, we have concentrated on rendering the same image at various sizes in order to reduce load times. This method, however, is ineffective when you want to display various images according to screen size. For instance, you might want to use a more detailed image on desktop than on mobile if your website has a large header that fills the entire width of the page. This issue is resolved by the picture element.

The picture element enables you to define multiple source elements that specify different images to use at various screen sizes. The browser will then select the first source element that matches the current screen size and display that image. If none of the source elements match the current screen size, the img defined in the picture element will be used as a fallback.

<picture>v
  <source media="(max-width: 500px)" srcset="hiking-narrow.jpg" />
  <img src="hiking-wide.jpg" alt="Someone jumping on a hike" />
</picture>

The image should alternate between the two versions we made if you change the size of your browser window. You might need to zoom in or out on a mobile device to see the change. Because the person in the image, which serves as the image's primary focus, would be too small to be visible on smaller screens, we created a more zoomed-in version of the image for those displays.

Now let's examine the code to see how it functions. To use a picture element, you must at least include a regular img tag within the picture element at the very end.

<picture>
  <img src="hiking-wide.jpg" alt="Someone jumping on a hike" />
</picture>

By following this approach, the image will be displayed in the same way as a regular img tag. However, it becomes more complex with the addition of the source element. For each version of the image, apart from the default one, you should have a separate source element. Although, in this particular example, only one source element was used, you can have as many source elements as required for your needs.

<picture>
  <source media="(max-width: 500px)" srcset="hiking-narrow.jpg" />
  <source media="(max-width: 1000px)" srcset="hiking-medium.jpg" />
  <img src="hiking-wide.jpg" alt="Someone jumping on a hike" />
</picture>

In each source element, there are two primary attributes. The first one, srcset, functions just like the img tag's srcset attribute. This implies that if there are numerous resolutions of the hiking-narrow.jpg image, they can be included in the srcset. However, when using the picture element, each source element typically only has one resolution, so it can be added as the sole URL in the srcset attribute.

The second attribute is the media attribute. This attribute operates similarly to media queries in the sizes attribute. However, with the media attribute in the source element, you can only specify one media query. These queries are subsequently examined from top to bottom, just like the sizes attribute, and the first one that matches is utilized. If none of the media queries match, the img tag is utilized as a fallback. This is why we don't have a source element specifically for larger screen sizes.

Reasons for Using the picture Element over Other Available Options

The picture element is sometimes confusing because people wonder why they should use it instead of the sizes attribute of the img element or CSS.

Reasons Why sizes Is Not a Suitable Alternative!

The picture element is preferred over the sizes attribute because it always swaps to the image specified in the matching source element based on the current screen size, even when the screen size changes. The sizes attribute works similarly but only when the screen size increases. If the screen size decreases, the browser will not switch to the smaller image as it already has the larger image, which saves bandwidth but can be problematic when different images are needed for different screen sizes. Therefore, the picture element is the ideal solution in such scenarios.

Reasons Why CSS Is Not a Suitable Alternative!

If you have knowledge of CSS, you may recognize that we can achieve a comparable outcome by applying some basic CSS properties.

img {
  object-fit: cover;
  object-position: center;
}

By using CSS, we can achieve a similar output where the image will fill the parent element's entire width and crop the image to always show the center of the image. However, the disadvantage of using CSS is that we still need to download the full-resolution version of the image even on small screens where only a small part of it is displayed. This defeats the purpose of using responsive images.

Conclusion: How to Speed Up Page Load

To summarize, responsive images may appear complicated, but they do not have to be. Basic responsive image implementation entails adding a srcset attribute to the img tag and letting the browser handle the rest. If you want to go a step further, you can use the sizes attribute to assist the browser in selecting the appropriate image, or you can use the picture element to display different images at different screen sizes.


This content originally appeared on DEV Community and was authored by Fatemeh Paghar


Print Share Comment Cite Upload Translate Updates
APA

Fatemeh Paghar | Sciencx (2023-06-04T16:51:57+00:00) Speeding Up Page Load and Reducing the Amount of Time it Takes Using Responsive Images. Retrieved from https://www.scien.cx/2023/06/04/speeding-up-page-load-and-reducing-the-amount-of-time-it-takes-using-responsive-images/

MLA
" » Speeding Up Page Load and Reducing the Amount of Time it Takes Using Responsive Images." Fatemeh Paghar | Sciencx - Sunday June 4, 2023, https://www.scien.cx/2023/06/04/speeding-up-page-load-and-reducing-the-amount-of-time-it-takes-using-responsive-images/
HARVARD
Fatemeh Paghar | Sciencx Sunday June 4, 2023 » Speeding Up Page Load and Reducing the Amount of Time it Takes Using Responsive Images., viewed ,<https://www.scien.cx/2023/06/04/speeding-up-page-load-and-reducing-the-amount-of-time-it-takes-using-responsive-images/>
VANCOUVER
Fatemeh Paghar | Sciencx - » Speeding Up Page Load and Reducing the Amount of Time it Takes Using Responsive Images. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/06/04/speeding-up-page-load-and-reducing-the-amount-of-time-it-takes-using-responsive-images/
CHICAGO
" » Speeding Up Page Load and Reducing the Amount of Time it Takes Using Responsive Images." Fatemeh Paghar | Sciencx - Accessed . https://www.scien.cx/2023/06/04/speeding-up-page-load-and-reducing-the-amount-of-time-it-takes-using-responsive-images/
IEEE
" » Speeding Up Page Load and Reducing the Amount of Time it Takes Using Responsive Images." Fatemeh Paghar | Sciencx [Online]. Available: https://www.scien.cx/2023/06/04/speeding-up-page-load-and-reducing-the-amount-of-time-it-takes-using-responsive-images/. [Accessed: ]
rf:citation
» Speeding Up Page Load and Reducing the Amount of Time it Takes Using Responsive Images | Fatemeh Paghar | Sciencx | https://www.scien.cx/2023/06/04/speeding-up-page-load-and-reducing-the-amount-of-time-it-takes-using-responsive-images/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.