Search code examples
javascriptjqueryhtmljquery-lazyload

Lazyload plugin against a background-image div is causing the content contained within the div to flicker when loading the image


I have a small but annoying issue. I'm using the Lazyload plugin for JQuery (Mika Tuupola - here) and I'm having an issue whereby using the fadeIn effect on a div background-image attribute causes the inner content to flicker when the image finally loads. It essentially reloads the content when the image loads. How do I avoid this?

My html extract:

<div class="wrap" id="wrap">    
    <div class="bg-image" data-original="images/image_1.jpg">
         <h1>Some title here</h1>
    </div>
    <div class="bg-image" data-original="images/image_1.jpg">
         <h1>Some other title here</h1>
    </div>
    <div class="bg-image" data-original="images/image_1.jpg">
         <h1>another title here</h1>
    </div>
</div>

My JS usage of Lazyload is against the container element because I have the structure above repeated several times (loading the same image):

$("div.bg-image").lazyload({
    container: $("#wrap"),
     threshold: 200,
    effect: "fadeIn"
});

For the most part it works well but the flicker is off putting somewhat. Hopefully that's enough detail, I'll see if I can get a a sample fiddle going (you may have to bear with me on that ...)


Solution

  • I'm the creator of another lazy load plugin for jQuery. You can't solve the problem this way. The problem is, that, when the outer div fades, the content will always will fade too. There is nothing you can do to prevent this.

    A possible solution is to put the background in another div in the back of the content boxes. So it will be visible as background, but it not really is. So there is an extra element for the background, which can be faded alone. Then the content will not fade too.

    Here is a quick example of what I mean:

    $(".bg").lazy({
      threshold  : 0,
      effect     : "fadeIn",
      effectTime : 500
    });
    .wrap > div {
      width: 500px;
      height: 250px;
      position: relative;
    }
    .bg {
      width: 500px;
      height: 250px;
      position: absolute;
      z-index: -1;
    }
    h1 {
      text-align: center;
      line-height: 250px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/jquery.lazy/1.7.3/jquery.lazy.min.js"></script>
    
    <div class="wrap" id="wrap">
      <div>
        <div class="bg" data-src="http://dummyimage.com/500x250/ff00a2/ff00a2&text=1"></div>
        <h1>Some title here</h1>
      </div>
      <div>
        <div class="bg" data-src="http://dummyimage.com/500x250/0099ff/0099ff&text=2"></div>
        <h1>Some other title here</h1>
      </div>
      <div>
        <div class="bg" data-src="http://dummyimage.com/500x250/45d104/45d104&text=3"></div>
        <h1>another title here</h1>
      </div>
    </div>