Question:
How to implement efficient infinite scroll in Firebase using javascript (and node.js)?
WHAT I CHECKED:
Implement infinite scroll with Firebase?
Problem: earlier firebase ^
Endless Scroll with AngularJs and Firebase
CODE FROM: Endless Scroll with AngularJs and Firebase
"First, I recommend creating an Index in your Firebase. For this answer, I create this:
{ "rules": { ".read": true, ".write": false, "messages": { ".indexOn": "id" } } }
Then do the magic with Firebase:
// @fb: your Firebase. // @data: messages, users, products... the dataset you want to do something with. // @_start: min ID where you want to start fetching your data. // @_end: max ID where you want to start fetching your data. // @_n: Step size. In other words, how much data you want to fetch from Firebase. var fb = new Firebase('https://<YOUR-FIREBASE-APP>.firebaseio.com/'); var data = []; var _start = 0; var _end = 9; var _n = 10; var getDataset = function() { fb.orderByChild('id').startAt(_start).endAt(_end).limitToLast(_n).on("child_added", function(dataSnapshot) { data.push(dataSnapshot.val()); }); _start = _start + _n; _end = _end + _n; }
Finally, the best infinite scroll (without jQuery):
window.addEventListener('scroll', function() { if (window.scrollY === document.body.scrollHeight - window.innerHeight) { getDataset(); } });
I use this approach with React and it flashes quickly no matter how big your data is.
(answered on October 26 15:15 at 15:02)
(by Jobsamuel)
PROBLEM
In this solution, n messages will be loaded every time the scroll reaches the end of the screen height.
Depending on the size of the screen, this means that at some point a lot more messages will be loaded than necessary (the height of the screen contains only 2 messages, which means that each time you reach the end of the screen 3 more messages will be downloaded, height with n = 5, for example).
This means that 3*NumberOfTimesScrollHeightHasBeenPassed
more messages than necessary will be loaded every time we reach the end of the scroll.
MY CURRENT CODE (downloads all messages at once, without endless scrolling):
var express = require("express"); var router = express.Router(); var firebase = require("firebase"); router.get('/index', function(req, res, next) { var pageRef = firebase.database().ref("posts/page"); pageRef.once('value', function(snapshot){ var page = []; global.page_name = "page"; snapshot.forEach(function(childSnapshot){ var key = childSnapshot.key; var childData = childSnapshot.val(); page.push({ id: key, title: childData.title, image: childData.image }); }); res.render('page/index',{page: page}); }); });