Lazy load technique with just 'three lines' of code

Javascript, 2015-06-17 00:05:10 UTC

In my opinion, lazyload is another way of pagination.

The concept of lazyload is loading the data as the request. The easiest way to implement lazy load is by requesting the data when the user scrolling the page down. For this concept, the data is ajax page which I wrote before.


This is how to make

1. HTML

<html>
    <head>
        <title>Lazy load</title> 
    </head> 
    <body>
        <div id="main_page"></div>
        <script src="app.js"><script> 
    </body> 
</html>




2. Javascript

//set the page for the first time
localStorage.setItem('page',0);

var xcore = {
    nextPage: function() {
        var page = parseInt(localStorage.getItem('page'))+1;
        localStorage.setItem('page',page); 
        $.ajax({
            url: '/ajax/products?page='+page+'&rows=10&of=created_at&od=desc',
            success: function(response) {
                $('#main_page').append(response);
            }
        });
    }
};


//lazy load
$(window).scroll(function() {
    if($(window).scrollTop() + $(window).height() > $(document).height() - 100 ) {
        xcore.nextPage();
    }  
});



Here I can tell you about the code;

1. When page load for the first time;
We know HTML load from the top to the bottom. So, when page load, it will load app.js and set page localStorage equals to zero for the first time. Next, the xcore is just a javascript object which is not executed yet. In the end, the application executed nextPage method for the first time and page plus one and then set it as new localStorage.

2. When user scroll down;
It will execute next page, looking for localStorage, requesting the data and the server response will append to main_page.


Share: