Skip to content

Instantly share code, notes, and snippets.

@ahomu
Last active December 16, 2015 03:39
Show Gist options
  • Save ahomu/5371263 to your computer and use it in GitHub Desktop.
Save ahomu/5371263 to your computer and use it in GitHub Desktop.
かきすて しかし、気がつけばスクロール同期+キュー管理へ。
/**
* Chikoque
*
* @author ahomu
*/
(function(win, doc, _) {
'use strict';
var defaults = {
dataAttribute: 'data-lazy',
parallelLimit: 5
};
var Chikoque = function(options) {
options || (options = {});
this.dataAttr = options.dataAttribute || defaults.dataAttribute;
this.limit = options.parallelLimit || defaults.parallelLimit;
window.addEventListener('scroll', _.throttle(_.bind(this.subscribe, this), 200), false);
this.subscribe();
};
function _createQueue(img, dataAttr) {
return function(done) {
img.onload = img.onerror = done;
img.setAttribute('src', img.getAttribute(dataAttr));
img.removeAttribute(dataAttr);
};
}
Chikoque.prototype.subscribe = function() {
var clientHeight = window.innerHeight || document.documentElement.clientHeight,
pageYOffset = window.pageYOffset,
from = pageYOffset - 200,
to = pageYOffset + clientHeight + 200,
imgYOffset;
this.idleLazies = [].slice.call(doc.querySelectorAll('img['+this.dataAttr+']'));
this.imgQueues = [];
var i = 0, img;
while ((img = this.idleLazies[i++])) {
imgYOffset = pageYOffset + img.getBoundingClientRect().top;
if (imgYOffset > from && imgYOffset < to) {
this.imgQueues.push(_createQueue(img, this.dataAttr));
}
}
if (this.imgQueues.length) {
this.kick();
}
};
Chikoque.prototype.kick = function() {
if (!this.running) {
this.run();
}
};
Chikoque.prototype.run = function() {
var that = this,
limit = this.limit,
running = 0;
this.running = true;
function onloadHandler() {
running--;
if (running < limit) {
nextQueue();
}
}
function nextQueue() {
var queue;
while ((queue = that.imgQueues.shift())) {
running++;
queue(onloadHandler);
if (running >= limit) {
break;
}
}
// if not exists remaining queues
if (!queue) {
that.running = false;
}
}
// start
nextQueue();
};
if (typeof define === 'function' && define.amd) {
define(function() {
return Chikoque;
});
} else {
win.Chikoque = Chikoque;
}
})(window, document, _);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment