Synchronous / Asynchronous Image Decode using〈img decoding〉Attribute

html
Published on December 13, 2019

Use-Cases of this tutorial

  • Know about the "decoding" attribute of the HTML <img> tag.
  • Know how to decode an image in parallel while page is being rendered.
  • Know how to improve rendering time of a page.

The decoding attribute for an <img> can specify whether to decode the image in parallel or along with the rest of the page content.

How Browser Renders an Image in Page

  • First the image is downloaded from the server.
  • Then image data is read (decoded).
  • Using the decoded data, image is rendered on page.

Controlling Image Decode through the decoding Attribute

The <img> tag can include a decoding attribute through which we can specify a hint to the browser whether decoding of the image should be done synchronously or asynchronously.

The decoding attribute can have 3 values :

  • sync : Decode the image synchronously in the main thread. Page rendering and image decoding happens one after the other (depending upon the position of image in the page).

    <!-- synchronously decode the image -->
    <img src="img/test.jpg" decoding="sync" >
    
  • async : Decode the image asynchronously. Rendering of page and decoding of image is done in parallel. This obviously makes the page to render faster.

    <!-- asynchronously decode the image -->
    <img src="img/test.jpg" decoding="async" >
    
  • auto : This is the default value. It is left to the browser to decide whether to decode the image synchronously or asynchronously.

    <!-- let the browser handle decoding method -->
    <img src="img/test.jpg" decoding="auto" >
    

Improve Page Performance with decoding Attribute

Decoding is an expensive operation. Until the image is decoded, the page remains in a non-responsive "frozen" state.

To improve rendering time of the page, decoding="async" can be specified to decode the image in parallel.

<!-- asynchronously decode the image -->
<img src="img/test.jpg" decoding="async" >

Asynchronous Image Loading and Decoding with Javascript ?

The decode() method can be used to load and decode an image using Javascript. See Pre-Loading and Pre-Decoding Images with Javascript for Better Performance for more.

In this Tutorial