Created
June 20, 2013 15:18
-
-
Save ahomu/5823669 to your computer and use it in GitHub Desktop.
いまいちだ...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Chikoque | |
* | |
* @author ahomu | |
*/ | |
(function(win, doc, _) { | |
'use strict'; | |
var defaults = { | |
dataAttribute: 'data-src', | |
parallelLimit: 5 | |
}; | |
// init queue | |
window.ckq = window.ckq || []; | |
var Chikoque = function(options) { | |
var tmp = window.ckq; | |
options || (options = {}); | |
this.dataAttr = options.dataAttribute || defaults.dataAttribute; | |
this.limit = options.parallelLimit || defaults.parallelLimit; | |
this.loadQueues = []; | |
window.ckq = { | |
queue: tmp, | |
push : function(item) { | |
window.ckq.queue.push(item); | |
} | |
}; | |
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, | |
detectMargin = clientHeight, | |
from = pageYOffset - detectMargin, | |
to = pageYOffset + clientHeight + detectMargin, | |
img, | |
imgYOffset, | |
notInViewportImgs = []; | |
while ((img = window.ckq.queue.shift())) { | |
imgYOffset = pageYOffset + img.getBoundingClientRect().top; | |
if (imgYOffset > from && imgYOffset < to) { | |
this.loadQueues.push(_createQueue(img, this.dataAttr)); | |
} else { | |
notInViewportImgs.push(img); | |
} | |
} | |
window.ckq.queue = notInViewportImgs; | |
if (this.loadQueues.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.loadQueues.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, _); |
Author
ahomu
commented
Jun 20, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment