PrimuS
PrimuS

Reputation: 2683

lazy loading images on scroll and "come into view"

I am using Lazy as a lazy image loading plugin. I have a div where I load divs like this:

<div class="nano-content" id="lScroll">

    /*... MORE LIKE THIS ... */
    <div class="card">
        <div class="city-selected city-medium clickChampion pointer"
     data-champ-id="1">
        <article>
            <div class="info">
                <div class="city">
                    CHAMPNAME
                </div>
            </div>
        </article>
            <figure class="cFigure lazy" data-src="images/champions/CHAMPNAME_0.png"></figure>
        </div>
    </div>
    /*... MORE LIKE THIS ... */

</div>

So I initiate the plugin and it works for the first ones visible and when I scroll:

var $lazy = $('#lScroll .lazy');
if ($lazy.length) {
    $lazy.Lazy({
        appendScroll: $('#lScroll')
    });
}

But now I have a function that "filters" the divs by their attributes when I enter sth in my search input and it fails to load the image when the according div is shown:

$(document).on("keyup", "#searchVod", function () {
    var $search = $(this);
    var $sVal = $search.val().toLowerCase();
    if ($sVal !== "") {
        $(".vodCard").hide();
        $('[data-champ*="' + $sVal + '"]').show();
        $('[data-role*="' + $sVal + '"]').show();
    } else {
        $(".vodCard").show();
    }
});

I tried bind: "event" /w and w/out delay: 0 (loading the plugin in the search function) but when I searched it would load ALL images immediately in the background.

Any hint highly appreciated

UPDATE: I just noticed in Chrome DevTab after entering one letter in my searchbox it loads ALL the images and eventually the one I am searching for (if its the last it takes some time (30MB sth)

Upvotes: 7

Views: 16243

Answers (1)

Idoshin
Idoshin

Reputation: 361

There is an excellent library called Lozad.js which can help you to make it easier to load your images like lazy load do but in easier way.

You can download it here from Github.

Demo page here.

Explanation:
This library will load your images one by one on scrolling to each image anchor by class name.

Example

HTML:
At the header ->

<script src="https://cdn.jsdelivr.net/npm/lozad"></script>  

Image element should looks like this:

<img class="lozad" data-src="image.png">

Javascript

// Initialize library
lozad('.lozad', {
    load: function(el) {
        el.src = el.dataset.src;
        el.onload = function() {
            el.classList.add('fade')
        }
    }
}).observe()

Hope it will help you.
Best,
Ido.

Upvotes: 6

Related Questions