So, I can't for the life of me figure out how to get a proper infinite scroll done with VueJS and vue-resource. My data is loading with VueJS and vue-resource, but the trigger on scroll and proper handling is the issue.
Does anybody know how to do this? All attempts I tried lead to loads of double requests and spamming my backend with repeat requests.
What I've tried so far:
Wrapping the "this.$http.get" request into a en event listener for window.scroll and a conditional within that, which checks if the bottom of the page is reached. This would alway double or even multi-trigger the get request instead of just one trigger and then waiting for load again.
Doing something similar but with an element at the very bottom of the list where I would check if it was in view. The same thing with multi-triggering get requests.
One solution would be to setup a locking mechanism to stop rapid requests to your backend. The lock would be enabled before a request is made, and then the lock would be disabled when the request has been completed and the DOM has been updated with the new content (which extends the size of your page).
For example:
new Vue({
// ... your Vue options.
ready: function () {
var vm = this;
var lock = true;
window.addEventListener('scroll', function () {
if (endOfPage() && lock) {
vm.$http.get('/myBackendUrl').then(function(response) {
vm.myItems.push(response.data);
lock = false;
});
};
});
};
});
Another thing to keep in mind is that the scroll
event is triggered more than you really need it to (especially on mobile devices), and you can throttle this event for improved performance. This can efficiently be done with requestAnimationFrame
:
;(function() {
var throttle = function(type, name, obj) {
obj = obj || window;
var running = false;
var func = function() {
if (running) { return; }
running = true;
requestAnimationFrame(function() {
obj.dispatchEvent(new CustomEvent(name));
running = false;
});
};
obj.addEventListener(type, func);
};
/* init - you can init any event */
throttle ("scroll", "optimizedScroll");
})();
// handle event
window.addEventListener("optimizedScroll", function() {
console.log("Resource conscious scroll callback!");
});
Source: https://developer.mozilla.org/en-US/docs/Web/Events/scroll#Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With