gists/2015.js.infinite-scroll.js

66 lines
1.8 KiB
JavaScript

/*jslint browser: true, indent: 4 */
/*
Example use of ScrollGuard: a simple, unobtrusive lazy loader.
Each time the user scrolled to the bottom of the page:
1. Look if there is content to load (lookForNextPage)
2. If new content, get content using Ajax (getNextPage)
3. Append the new content and do some polish (appencContent)
*/
(function (g) {
"use strict";
var lookForNextPage,
getNextPage,
appendContent;
if (g.ScrollGuard === undefined) {
throw new Error("scrollguard.js is required!");
}
appendContent = function (content) {
var body, rows, i, max, newContent, table;
body = document.createElement("div");
body.innerHTML = content;
newContent = document.createDocumentFragment();
rows = body.querySelectorAll(".main-c table tr");
for (i = 1, max = rows.length; i < max; i += 1) {
newContent.appendChild(rows[i]);
}
table = document.querySelector(".main-c table").tBodies[0];
table.replaceChild(newContent, table.querySelector("tr.pagination"));
};
lookForNextPage = function () {
var nextPage = document.getElementById("pager-next");
if (nextPage) {
getNextPage(nextPage.href);
}
};
getNextPage = function (href) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status === 200 || request.status === 304) {
appendContent(request.responseText);
}
}
};
request.open("GET", href, true);
request.send(null);
};
if (document.getElementById("pager-next")) {
g.ScrollGuard.add(lookForNextPage, -1);
g.ScrollGuard.start();
}
}(this));