Lazy Loading (Load On-Demand)


A simple mock-up for Lazy Loading (Load On Demand using vertical scroll-bar):

Running Sample in: http://jsfiddle.net/clemskie/VL2BL/

HTML:

<div id='container' style='border: solid 1px gray;height:100px;overflow:auto;'>
    <table id='theTable'>
        <thead>
            <th>ID</th>
            <th>NAME</th>
        </thead>
        <tbody></tbody>
    </table>
</div>
<button onclick='MyPageController.loadInitialDisplay();'> Reset
</button>


JAVASCRIPT:

window.MyPageController = {
    recordsPerPage: 5,
    rowCtr: 0,
    container: $('#container'),
    theTable: $('#theTable'),
    clearTable: function () {
        $(theTable).children('tbody').remove();
    },
    loadInitialDisplay: function () {
        this.container.scrollTop(0);
        this.rowCtr = 0;
        this.clearTable();
        this.loadNextSetOfRecords();
    },
    loadNextSetOfRecords: function () {
        for (var i = 1; i <= this.recordsPerPage; i++) {
            this.rowCtr++;
            var tr = $('');
            var tdID = $('<td />', {html: this.rowCtr});
            var tdName = $('<td />', {html: 'Name' + this.rowCtr});
            tr.append(tdID, tdName);
            $(theTable).append(tr);
        }
    }
};

function scrollHandler(container) {
    var st = container.scrollTop;
    var scrollHeight = container.scrollHeight;
    var containerHeight = container.clientHeight;
    if (st >= scrollHeight - containerHeight) {
        MyPageController.loadNextSetOfRecords();
    }
}

$(function () {
    MyPageController.loadInitialDisplay();
    MyPageController.container.on('scroll', function(event){
          scrollHandler(this);
    });
});






No comments:

Post a Comment