Problem:
Loading a large record dataset on a page can slow down the
app quite a bit. How can I load a small
number of records incrementally when the user scrolls to the end of the page?
Solution:
Infinite scrolling! Most Facebook users experience infinite scrolling
as they scroll to view posts. This is made easy using jQuery.
The Code:
Consider this event handler:
$(window).scroll(function () {
if($(document).height() <= $(window).height()+300)
{
}
});
If the height of the page reached the window height + 300
(or, scrolled to about 2/3 of the page), then do something. In my case, I would make a service call for the next 3 records (assuming the record count on load was 3 records). Let’s say, records 4 to 6. Here’s the completed code:
var currentPage = 1;
$(window).scroll(function () { if ($(document).height() <= $(window).height()+300) { $.ajax('http://www.somesite.com/myservice', { data: { total: '3', // only 100 at a time start: (4 * currentPage) }, success: function(data) { appendNewRecords(data.results); //add to existing records } }); currentPage++; //setting up next set } }); function appendNewRecords(results){ results.forEach(function(record){ $(body).append('<div>' + record.name + '</div>'); }); }
Here's the new html rendering:
<html>
<head>
<title>example</title>
</head>
<body>
<div>Tom</div> <!--rendered on load-->
<div>Dick</div>
<div>Harry</div>
<div>Larry</div> <!-- added after scroll event is triggered-->
<div>Mo</div>
<div>Curly</div>
</body>
</html>
Hope this helps!
References:
Comments
Post a Comment