Search code examples
javascriptjqueryhtmlcssjquery-lazyload

jQuery.Lazy() - lazy load background image of section with id


I want to apply lazy loading for one image with method .lazy() for a section with id. The section has configured background via CSS. Below is code:

HTML

  <section id="showcase">
  </section>

CSS

/* Showcase*/
#showcase {
  min-height: 400px;
  background: url("../img/example.jpg") no-repeat -300px -500px;
  background-size: cover;
}

JS

<script>
  $(function() {
     $("#showcase").lazy();
  });
 </script>

How should I change the code? Because now it doesn´t work. It is working only when I have a code and a tag <img class="lazy" data-src="../img/example.jpg" /> as you can see in an example below:

http://jquery.eisbehr.de/lazy/example_basic-usage


Solution

  • According to the JQuery.Lazy docs and demos in their website, you could load background images by setting the data-src attribute to the element on which you want to load the background image.

    So in your case you could do as follows:

    <section id="showcase" data-src="../img/example.jpg"></section>
    

    Then you will need to remove the background-image definition from the css style.

    You can check their working example on their website.