Skip to content

Instantly share code, notes, and snippets.

@lean8086
Last active December 14, 2015 11:09
Show Gist options
  • Save lean8086/5076949 to your computer and use it in GitHub Desktop.
Save lean8086/5076949 to your computer and use it in GitHub Desktop.
Progressive image loader + infinite scroll
(function (win) {
'use strict';
var doc = win.document,
scrollTop,
pagination = doc.getElementsByClassName('pagination')[0],
loadingPosts = false,
xhr = new win.XMLHttpRequest(),
page = 1,
nextHref = win.location.href + (win.location.pathname === '/' ? '' : '/') + 'page/';
if (pagination !== undefined) {
pagination.parentNode.removeChild(pagination);
}
function loadHighRes() {
var imgs = doc.querySelectorAll('[data-async]'),
i = imgs.length,
img;
while (i) {
img = imgs[i -= 1];
img.onload = function () {
this.removeAttribute('width');
this.removeAttribute('height');
this.removeAttribute('data-async');
};
img.src = img.dataset.async;
if (img.complete) {
img.onload();
img.onload = null;
}
}
}
function loadPosts() {
if (loadingPosts) { return; }
loadingPosts = true;
xhr.open('GET', nextHref + (page += 1), true);
xhr.send();
}
function checkScroll() {
scrollTop = (win.pageYOffset || doc.documentElement.scrollTop || 0);
if (doc.height - (win.innerHeight + scrollTop) < win.innerHeight * 2) {
loadPosts();
}
}
xhr.onload = function () {
if (this.status !== 200) { return; }
var response = this.response.replace(/(\s\s)+/g, ' '),
articles = response.match(/<article>(.*?)<\/article>/ig);
if (articles && articles.length > 0) {
doc.body.innerHTML += articles.join('');
loadHighRes();
loadingPosts = false;
}
};
win.addEventListener('resize', checkScroll);
win.addEventListener('scroll', checkScroll);
win.addEventListener('load', loadHighRes);
}(this));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment