The HTML decoding attribute
An <img> can appear with other content or after it, and the HTML decoding attribute states which you prefer. The value sync asks for the image to appear with other content, async lets other content appear first, and auto, the default, leaves the choice to the browser.
Overview
The HTML decoding attribute expresses a preference for how an <img> is decoded. Decoding is the step that turns an image's data into pixels. The attribute takes sync, async or auto, and auto is the default.
With sync, you ask for other content to wait until the image is decoded, so that everything appears at once. With async, you ask for the rest of the page to be shown first, and the image fills in when its decode finishes.
On an image written in the HTML, the difference is often hard to see. Such images usually show up empty while the file downloads and are then handled on their own, so the effect is clearer on images that JavaScript inserts.
Browsers are expected to respect the preference the attribute states, and with auto they are free to choose any decoding behavior.
Syntax
<img src="lake.jpg" alt="Mountain lake at dawn" decoding="async">
Values
| Value |
|---|
| auto (default) | sync | async |
Example
<img id="main" src="lake.jpg" alt="Mountain lake at dawn" width="800" height="450" decoding="async">
<button type="button" id="next">Show the next photo</button>
<script>
document.getElementById('next').addEventListener('click', async function () {
const photo = new Image(800, 450);
photo.decoding = 'async';
photo.src = 'forest.jpg';
photo.alt = 'Pine forest in fog';
try {
await photo.decode();
photo.id = 'main';
document.getElementById('main').replaceWith(photo);
} catch (error) {
console.error('The next photo could not be decoded.');
}
});
</script>
Best practices
- Apply
decoding="async"to a large image that a script inserts while other content is changing. This may keep other content from being held up by a long decode. - Switch to
decoding="sync"when an inserted image must appear in the same update as the content around it. Load the image first, set sync, and then insert it. - Prefer
img.decode()when you swap one image for another. It works better than the attribute here, because you can wait until the image is downloaded and decoded before you insert it. - Stick to sync, async and auto. Browsers read any other value, such as fast, as auto, and validator.nu rejects it.























