Hello friends, in this article we will learn lazy loading in SharePoint. Many times, some customers want to develop a portal using SharePoint which loads fast without loading components that are not visible on the screen. We need to load those components if the user scrolls the page downwards. So least learn how to implement Lazy loading in SharePoint.

How to implement Lazy Loading in SharePoint


The below script can be used for lazy loading in SharePoint. It is applicable for SharePoint online, SharePoint 2010, 2013, 2016, 2019 and SharePoint online. You need to make the change in line number 10 with the class name for your component.

Instead of calling generateEmployeeTable() function directly on-page load, call lazyLoadingEmployeeTable() so that it will wait for the scroll event and then load generateEmployeeTable() function. See the below script which does the same.

$(document).ready(function () {
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', lazyLoadingEmployeeTable);
});

function lazyLoadingEmployeeTable() {

    var winHgtRef = $("#s4-workspace").height() * 0.95;
    // get the context reference of web part we are loading
    var $wp = $('.employee-table');
    var scroller = 'scroll.ll' + Math.random();

    // check if currently visible, if so, fire up the loading
    if ($wp.offset().top < winHgtRef) {
        generateEmployeeTable();
        return;
    }

    $("#s4-workspace").on(scroller, function () {

        // variables for this context
        var winTop = $("#s4-workspace").scrollTop();
        var itemOffset = $wp.offset().top;
        var winContHgt = $("#s4-workspace").height();
        var scrollTrigger = 0.95;
        var pos = (winTop / (itemOffset - winContHgt));
        if (pos > scrollTrigger || pos < 0) {
            generateEmployeeTable();
            $("#s4-workspace").off(scroller);

        }
    });
}

function generateEmployeeTable(){
    //your function
    //some code
}