🐛 Fixed infinitescroll when a paged url is loaded directly (#447)

closes #445
- added an fn to sanitize the pathname, that might include a pagination url
- fixed an issue, where the request would still be made if the current page is bigger than max pages
- added comments
This commit is contained in:
Aileen Nowak 2018-04-10 17:04:43 +08:00 committed by Kevin Ansfield
parent 41bcbb7157
commit d5002f2c51
2 changed files with 37 additions and 6 deletions

View File

@ -1,3 +1,5 @@
/* global maxPages */
// Code snippet inspired by https://github.com/douglasrodrigues5/ghost-blog-infinite-scroll
$(function ($) {
var currentPage = 1;
@ -13,9 +15,6 @@ $(function ($) {
var lastWindowHeight = window.innerHeight;
var lastDocumentHeight = $document.height();
// remove hash params from pathname
pathname = pathname.replace(/#(.*)$/g, '').replace('/\//g', '/');
function onScroll() {
lastScrollY = window.scrollY;
requestTick();
@ -34,7 +33,29 @@ $(function ($) {
ticking = true;
}
function sanitizePathname(path) {
var paginationRegex = /(?:page\/)(\d)(?:\/)$/i;
// remove hash params from path
path = path.replace(/#(.*)$/g, '').replace('////g', '/');
// remove pagination from the path and replace the current pages
// with the actual requested page. E. g. `/page/3/` indicates that
// the user actually requested page 3, so we should request page 4
// next, unless it's the last page already.
if (path.match(paginationRegex)) {
currentPage = parseInt(path.match(paginationRegex)[1]);
path = path.replace(paginationRegex, '');
}
return path;
}
function infiniteScroll() {
// sanitize the pathname from possible pagination or hash params
pathname = sanitizePathname(pathname);
// return if already loading
if (isLoading) {
return;
@ -46,15 +67,22 @@ $(function ($) {
return;
}
// return if currentPage is the last page already
if (currentPage === maxPages) {
/**
* maxPages is defined in default.hbs and is the value
* of the amount of pagination pages.
* If we reached the last page or are past it,
* we return and disable the listeners.
*/
if (currentPage >= maxPages) {
window.removeEventListener('scroll', onScroll, {passive: true});
window.removeEventListener('resize', onResize);
return;
}
isLoading = true;
// next page
currentPage++;
currentPage += 1;
// Load more
var nextPage = pathname + 'page/' + currentPage + '/';

View File

@ -65,6 +65,9 @@
{{#if pagination.pages}}
<script>
// maxPages is a global variable that is needed to determine
// if we need to load more pages for the infinitescroll, or if
// we reached the last page already.
var maxPages = parseInt('{{pagination.pages}}');
</script>
<script src="{{asset "js/infinitescroll.js"}}"></script>