Search code examples
htmlcssweb-performance

Can I prevent loading an entire image on a web page?


I have a masthead background image on my web page that only about 1/3 of the image is within the bounds to be seen on the page.

Is there any way to load just the slice of the image I need instead of the entire image loading? Google's page speed insights says my image is the main reason my home page is taking so long to load the first time around.

CSS:

header.masthead {
  position: relative;
  background-color: #343a40;
  background: url("../images/showcase.jpg") no-repeat center center;
  background-size: cover;
  padding-top: 8rem;
  padding-bottom: 8rem;
}

HTML:

  <header class="masthead">
    <div class="overlay"></div>
    <div class="container">
      <div class="row text-center">
        <div class="col-xl-9 mx-auto">
          <h1 class="text-light" >Lorem</h1>
        </div>
            <div class="row text-center">
              <div class="col-md-12">
                <a href="{{ url_for('billing.pricing') }}"><button type="submit" class="btn btn-main">Ipsum</button></a>
              </div>

        </div>
  </div>
</div>


Solution

  • Is there any way to load just the slice of the image I need instead of the entire image loading?

    Short answer: no.

    If you're only displaying 1/3 of your image and that applies to all devices, cropping the image is probably your best bet.

    If you want to fine-tune further, consider optimizing your image size and using srcset to offer multiple alternatives to the client browser.