Pagination

This commit is contained in:
Sodbileg Gansukh 2022-09-14 16:58:21 +08:00
parent 25a0f3338d
commit ed5b3cd102
3 changed files with 70 additions and 5 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -4,6 +4,71 @@ function initParallax() {
}); });
} }
function pagination(isInfinite = true, done) {
let loading = false;
const feedElement = document.querySelector('.gh-feed');
const target = feedElement.nextElementSibling || feedElement.parentElement.nextElementSibling;
const loadNextPage = async function () {
const nextElement = document.querySelector('link[rel=next]');
if (!nextElement) {
return;
}
try {
const res = await fetch(nextElement.href);
const html = await res.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const posts = doc.querySelectorAll('.gh-feed > *');
posts.forEach(function (post) {
feedElement.appendChild(document.importNode(post, true));
});
if (done) {
done();
}
const resNextElement = doc.querySelector('link[rel=next]');
if (resNextElement && resNextElement.href) {
nextElement.href = resNextElement.href;
} else {
nextElement.remove();
}
} catch (e) {
nextElement.remove();
throw e;
}
};
const callback = async function (entries) {
if (loading) {
return;
}
loading = true;
if (entries[0].isIntersecting) {
// keep loading next page until target is out of the viewport or we've loaded the last page
while (target.getBoundingClientRect().top <= window.innerHeight && document.querySelector('link[rel=next]')) {
await loadNextPage();
}
}
loading = false;
if (!document.querySelector('link[rel=next]')) {
observer.disconnect();
}
};
const observer = new IntersectionObserver(callback);
observer.observe(target);
}
(function () { (function () {
initParallax(); initParallax();
})(); })();
@ -34,6 +99,6 @@ function initParallax() {
element.innerHTML = text; element.innerHTML = text;
})(); })();
// (function () { (function () {
// pagination(true); pagination(true, initParallax);
// })(); })();