Skip to content

Instantly share code, notes, and snippets.

@tivac
Last active December 17, 2015 13:19
Show Gist options
  • Save tivac/5616180 to your computer and use it in GitHub Desktop.
Save tivac/5616180 to your computer and use it in GitHub Desktop.
Image lazy-loader
/*jshint browser:true, yui:true */
YUI.add("plugin-lazy-images", function(Y) {
"use strict";
var plugins = Y.namespace("GW2.Plugins"),
LazyImages;
LazyImages = Y.Base.create("lazyImages", Y.Plugin.Base, [], {
// Y.Base lifecycle fns
initializer : function() {
var host = this.get("host");
host.plug(Y.Plugin.ScrollInfo, {
scrollMargin : this.get("distance")
});
this._handles = [
host.scrollInfo.after([ "scrollDown", "scrollUp" ], this.loadVisible, this)
];
},
destructor : function() {
this.get("host").unplug(Y.Plugin.ScrollInfo);
new Y.EventTarget(this._handles).detach();
this._handles = null;
},
// Duplicate of nodeScrollInfo's .getOnscreenNodes() but without a bug
// TODO: remove when https://github.com/yui/yui3/issues/767 is fixed
getOnscreenNodes: function (selector, margin) {
var scrollInfo = this.get("host").scrollInfo;
if(typeof margin === "undefined") {
margin = scrollInfo._scrollMargin;
}
var lastScroll = scrollInfo._lastScroll,
nodes = scrollInfo._host.all(selector || "*"),
scrollBottom = lastScroll.scrollBottom + margin,
scrollLeft = lastScroll.scrollLeft - margin,
scrollRight = lastScroll.scrollRight + margin,
scrollTop = lastScroll.scrollTop - margin,
self = scrollInfo;
return nodes.filter(function (el) {
var rect = el.getBoundingClientRect(),
elLeft = rect.left - self._left + scrollLeft,
elTop = rect.top - self._top + scrollTop,
elBottom = elTop + rect.height,
elRight = elLeft + rect.width;
// Check whether the element's top left point is within the
// viewport.
if ((elLeft >= scrollLeft && elLeft < scrollRight &&
elTop >= scrollTop && elTop < scrollBottom) ||
// Check whether the element's bottom right point is within the
// viewport.
(elRight < scrollRight && elRight >= scrollLeft &&
elBottom < scrollBottom && elBottom >= scrollTop)) {
return true;
}
// If we get here, the element isn't within the viewport.
return false;
});
},
// Public API
loadVisible : function() {
this.getOnscreenNodes("[data-src]").each(function(img) {
img.set("src", img.getData("src"));
img.removeAttribute("data-src");
});
}
}, {
NS : "lazyimg",
ATTRS : {
distance : {
value : 100
}
}
});
plugins.LazyImages = LazyImages;
}, "@VERSION@", {
requires : [
// YUI
"base-build",
"plugin",
"node-scroll-info"
]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment