1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I tried that but it doesn´t work for me. Here is my code: HTML <section id="showcase" data-src="../img/example.jpg"></section> CSS #showcase { min-height: 400px; background: no-repeat -300px -500px; background-size: cover;} Javascript <script> $(function() { $("#showcase").lazy(); }); </script> Can you see what is wrong?
@M.Falex can you check the console for errors? Does the background images get loaded? (Check the network tab on the console).
In console no errors. Yes, the image gets loaded. But it is loaded two times. One time from index.html and second time is initiator jquery.min.js.
@M.Falex and how does the image gets loaded from the html? The image is not included there or in the css, am i right? Try removing the background css property and add the properties using background-position and background-repeat.
Now, it is working. Problem was that I forgot on another calling background image in @media segment. Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.