Search code examples
javascripthttpwebpng

HTTP Response with Multiple Layout Images in one PNG Image


I was playing around inspecting amazon.com http responses and I noticed this HERE as you can see the images used in the page layout are contained in one PNG image,

screenshot from chrome devtools

  • Is this a known approach ?

  • As I imagine, The JavaScript on the page will place each part of the image in the right place accoarding to a specific X&Y positions in that image, Is this really what's happening ?

  • Why are they doing this instead of requesting each image ? Is a new request more expensive than in-browser image processing ? (if my above assumption is correct)

  • Suggestions for further reading on this thing is much appreciated

Thanks!


Solution

  • Is this a known approach ?

    Yes. These are called CSS sprites. They reduce the number of image requests made by only requesting a single image and then only displaying the parts of the image that are needed.

    As I imagine, The JavaScript on the page will place each part of the image in the right place accoarding to a specific X&Y positions in that image, Is this really what's happening ?

    Yes. Correct. Well, maybe. Could be Javascript, but a CSS-only solution is more common.

    Why are they doing this instead of requesting each image ? Is a new request more expensive than in-browser image processing ? (if my above assumption is correct)

    Yes. Correct. Less requests means faster page loads, typically.

    Suggestions for further reading on this thing is much appreciated

    Here's a tutorial: https://css-tricks.com/css-sprites/

    Here's the example from that tutorial:

    .flags-canada, .flags-mexico, .flags-usa {
      background-image: url('https://i0.wp.com/css-tricks.com/wp-content/uploads/2009/10/sprite.png');
      background-repeat: no-repeat;
    }
    
    .flags-canada {
      height: 128px;
      background-position: -5px -5px;
    }
    
    .flags-usa {
      height: 135px;
      background-position: -5px -143px;
    }
    
    .flags-mexico {
      height: 147px;
      background-position: -5px -288px;
    }
    <h3>Full image</h3>
    <img src='https://i0.wp.com/css-tricks.com/wp-content/uploads/2009/10/sprite.png'>
    
    <h3>Canada</h3>
    <div class='flags-canada'></div>
    
    <h3>USA</h3>
    <div class='flags-usa'></div>
    
    <h3>Mexico</h3>
    <div class='flags-mexico'></div>