Wonko the Sane
Wonko the Sane

Reputation: 832

Working example of datatables with lazy loading of images

I'm looking for a working example of lazy-loading of images within datatables that continues to work after clicking on a column heading to change the sorting.

The method I've had the most success with uses the jquery.lazyload plug:

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
<script type="text/javascript">
    $(function() {
    $("img.lazy").lazyload();
    });
</script>   

Here's how I reference the image:

<img class="lazy" data-original="https://example.com/image.jpg" width="50" height="50" />

The lazy loading works fine if I never change the sorting. However, if I decide to change the sorting of the table by clicking on one of the column headings, the lazy loading stops working and any images that were not downloaded at this point will remain blank when I scroll them into view.

I wasn't born a javascript or jQuery expert, so had to learn from examples here on SO and elsewhere. But this problem stumps me. From my research, I see a lot of comments and snippets about how it is possible, but no actual working example that proves this is supported.

jquery-lazyload images in jquery-databables

https://datatables.net/forums/discussion/1959/image-thumbs-in-table-column-lazy-loading

I wont rattle off the numerous other links I found here and elsewhere, I just need some kind soul to help.

Upvotes: 4

Views: 9465

Answers (2)

Gyrocode.com
Gyrocode.com

Reputation: 58900

Use drawCallback option to define a function that will be called every time DataTables performs a draw.

For example:

$('.table-data').DataTable({
   drawCallback: function(){
        $("img.lazy").lazyload();
   }
});

See this jsFiddle for code and demonstration.

Upvotes: 18

annoyingmouse
annoyingmouse

Reputation: 5699

I'm sort of stuck with this one seeing as I don't have access to your backend or more information about your circumstances but I think what will work will be to call your lazy load code in the draw event like this:

$(document).ready(function() {
    $("img.lazy").lazyload();
    $('.table-data').DataTable({
        "drawCallback": function(){
            $("img.lazy").lazyload();
            setTimeout(function(){
                $(window).trigger("scroll")
            }, 1000);
        }
    });
});

I've got an example up here, but I think you might be using server-side processing?

Upvotes: 0

Related Questions