3
Copyright 2011 Yahoo! Inc. All rights reserved.
4
Licensed under the BSD License.
5
http://yuilibrary.com/license/
7
YUI.add('imageloader', function(Y) {
10
* The ImageLoader Utility is a framework to dynamically load images according to certain triggers,
11
* enabling faster load times and a more responsive UI.
18
* A group for images. A group can have one time limit and a series of triggers. Thus the images belonging to this group must share these constraints.
23
Y.ImgLoadGroup = function() {
24
// call init first, because it sets up local vars for storing attribute-related info
26
Y.ImgLoadGroup.superclass.constructor.apply(this, arguments);
29
Y.ImgLoadGroup.NAME = 'imgLoadGroup';
31
Y.ImgLoadGroup.ATTRS = {
34
* Name for the group. Only used to identify the group in logging statements.
43
* Time limit, in seconds, after which images are fetched regardless of trigger events.
44
* @attribute timeLimit
52
* Distance below the fold for which images are loaded. Images are not loaded until they are at most this distance away from (or above) the fold.
53
* This check is performed at page load (domready) and after any window scroll or window resize event (until all images are loaded).
54
* @attribute foldDistance
58
validator: Y.Lang.isNumber,
59
setter: function(val) { this._setFoldTriggers(); return val; },
64
* Class name that will identify images belonging to the group. This class name will be removed from each element in order to fetch images.
65
* This class should have, in its CSS style definition, "<code>background:none !important;</code>".
66
* @attribute className
71
setter: function(name) { this._className = name; return name; },
76
* Determines how to act when className is used as the way to delay load images. The "default" action is to just
77
* remove the class name. The "enhanced" action is to remove the class name and also set the src attribute if
78
* the element is an img.
79
* @attribute classNameAction
91
* Initialize all private members needed for the group.
98
* Collection of triggers for this group.
99
* Keeps track of each trigger's event handle, as returned from <code>Y.on</code>.
100
* @property _triggers
107
* Collection of images (<code>Y.ImgLoadImgObj</code> objects) registered with this group, keyed by DOM id.
115
* Timeout object to keep a handle on the time limit.
120
this._timeout = null;
123
* DOM elements having the class name that is associated with this group.
124
* Elements are stored during the <code>_foldCheck</code> function and reused later during any subsequent <code>_foldCheck</code> calls - gives a slight performance improvement when the page fold is repeatedly checked.
125
* @property _classImageEls
129
this._classImageEls = null;
132
* Keep the CSS class name in a member variable for ease and speed.
133
* @property _className
137
this._className = null;
140
* Boolean tracking whether the window scroll and window resize triggers have been set if this is a fold group.
141
* @property _areFoldTriggersSet
145
this._areFoldTriggersSet = false;
148
* The maximum pixel height of the document that has been made visible.
149
* During fold checks, if the user scrolls up then there's no need to check for newly exposed images.
150
* @property _maxKnownHLimit
154
this._maxKnownHLimit = 0;
156
// add a listener to domready that will start the time limit
157
Y.on('domready', this._onloadTasks, this);
161
* Adds a trigger to the group. Arguments are passed to <code>Y.on</code>.
164
* @param {Object} obj The DOM object to attach the trigger event to
165
* @param {String} type The event type
167
addTrigger: function(obj, type) {
168
if (! obj || ! type) {
173
/* Need to wrap the fetch function. Event Util can't distinguish prototyped functions of different instantiations.
174
* Leads to this scenario: groupA and groupZ both have window-scroll triggers. groupZ also has a 2-sec timeout (groupA has no timeout).
175
* groupZ's timeout fires; we remove the triggers. The detach call finds the first window-scroll event with Y.ILG.p.fetch, which is groupA's.
176
* groupA's trigger is removed and never fires, leaving images unfetched.
178
var wrappedFetch = function() {
181
this._triggers.push( Y.on(type, wrappedFetch, obj, this) );
187
* Adds a custom event trigger to the group.
188
* @method addCustomTrigger
190
* @param {String} name The name of the event
191
* @param {Object} obj The object on which to attach the event. <code>obj</code> is optional - by default the event is attached to the <code>Y</code> instance
193
addCustomTrigger: function(name, obj) {
199
// see comment in addTrigger()
200
var wrappedFetch = function() {
203
if (Y.Lang.isUndefined(obj)) {
204
this._triggers.push( Y.on(name, wrappedFetch, this) );
207
this._triggers.push( obj.on(name, wrappedFetch, this) );
214
* Sets the window scroll and window resize triggers for any group that is fold-conditional (i.e., has a fold distance set).
215
* @method _setFoldTriggers
218
_setFoldTriggers: function() {
219
if (this._areFoldTriggersSet) {
224
var wrappedFoldCheck = function() {
227
this._triggers.push( Y.on('scroll', wrappedFoldCheck, window, this) );
228
this._triggers.push( Y.on('resize', wrappedFoldCheck, window, this) );
229
this._areFoldTriggersSet = true;
233
* Performs necessary setup at domready time.
234
* Initiates time limit for group; executes the fold check for the images.
235
* @method _onloadTasks
238
_onloadTasks: function() {
239
var timeLim = this.get('timeLimit');
240
if (timeLim && timeLim > 0) {
241
this._timeout = setTimeout(this._getFetchTimeout(), timeLim * 1000);
244
if (! Y.Lang.isUndefined(this.get('foldDistance'))) {
250
* Returns the group's <code>fetch</code> method, with the proper closure, for use with <code>setTimeout</code>.
251
* @method _getFetchTimeout
252
* @return {Function} group's <code>fetch</code> method
255
_getFetchTimeout: function() {
257
return function() { self.fetch(); };
261
* Registers an image with the group.
262
* Arguments are passed through to a <code>Y.ImgLoadImgObj</code> constructor; see that class' attribute documentation for detailed information. "<code>domId</code>" is a required attribute.
263
* @method registerImage
264
* @param {Object} * A configuration object literal with attribute name/value pairs (passed through to a <code>Y.ImgLoadImgObj</code> constructor)
265
* @return {Object} <code>Y.ImgLoadImgObj</code> that was registered
267
registerImage: function() {
268
var domId = arguments[0].domId;
274
this._imgObjs[domId] = new Y.ImgLoadImgObj(arguments[0]);
275
return this._imgObjs[domId];
279
* Displays the images in the group.
280
* This method is called when a trigger fires or the time limit expires; it shouldn't be called externally, but is not private in the rare event that it needs to be called immediately.
285
// done with the triggers
286
this._clearTriggers();
288
// fetch whatever we need to by className
289
this._fetchByClass();
291
// fetch registered images
292
for (var id in this._imgObjs) {
293
if (this._imgObjs.hasOwnProperty(id)) {
294
this._imgObjs[id].fetch();
300
* Clears the timeout and all triggers associated with the group.
301
* @method _clearTriggers
304
_clearTriggers: function() {
305
clearTimeout(this._timeout);
306
// detach all listeners
307
for (var i=0, len = this._triggers.length; i < len; i++) {
308
this._triggers[i].detach();
313
* Checks the position of each image in the group. If any part of the image is within the specified distance (<code>foldDistance</code>) of the client viewport, the image is fetched immediately.
317
_foldCheck: function() {
319
var allFetched = true,
320
viewReg = Y.DOM.viewportRegion(),
321
hLimit = viewReg.bottom + this.get('foldDistance'),
322
id, imgFetched, els, i, len;
324
// unless we've uncovered new frontiers, there's no need to continue
325
if (hLimit <= this._maxKnownHLimit) {
328
this._maxKnownHLimit = hLimit;
330
for (id in this._imgObjs) {
331
if (this._imgObjs.hasOwnProperty(id)) {
332
imgFetched = this._imgObjs[id].fetch(hLimit);
333
allFetched = allFetched && imgFetched;
338
if (this._className) {
339
if (this._classImageEls === null) {
340
// get all the relevant elements and store them
341
this._classImageEls = [];
342
els = Y.all('.' + this._className);
343
els.each( function(node) { this._classImageEls.push( { el: node, y: node.getY(), fetched: false } ); }, this);
345
els = this._classImageEls;
346
for (i=0, len = els.length; i < len; i++) {
347
if (els[i].fetched) {
350
if (els[i].y && els[i].y <= hLimit) {
351
//els[i].el.removeClass(this._className);
352
this._updateNodeClassName(els[i].el);
353
els[i].fetched = true;
361
// if allFetched, remove listeners
363
this._clearTriggers();
368
* Updates a given node, removing the ImageLoader class name. If the
369
* node is an img and the classNameAction is "enhanced", then node
370
* class name is removed and also the src attribute is set to the
371
* image URL as well as clearing the style background image.
372
* @method _updateNodeClassName
373
* @param node {Node} The node to act on.
376
_updateNodeClassName: function(node){
379
if (this.get("classNameAction") == "enhanced"){
381
if (node.get("tagName").toLowerCase() == "img"){
382
url = node.getStyle("backgroundImage");
383
/url\(["']?(.*?)["']?\)/.test(url);
385
node.set("src", url);
386
node.setStyle("backgroundImage", "");
390
node.removeClass(this._className);
394
* Finds all elements in the DOM with the class name specified in the group. Removes the class from the element in order to let the style definitions trigger the image fetching.
395
* @method _fetchByClass
398
_fetchByClass: function() {
399
if (! this._className) {
404
Y.all('.' + this._className).each(Y.bind(this._updateNodeClassName, this));
410
Y.extend(Y.ImgLoadGroup, Y.Base, groupProto);
413
//------------------------------------------------
417
* Image objects to be registered with the groups
418
* @class ImgLoadImgObj
422
Y.ImgLoadImgObj = function() {
423
Y.ImgLoadImgObj.superclass.constructor.apply(this, arguments);
427
Y.ImgLoadImgObj.NAME = 'imgLoadImgObj';
429
Y.ImgLoadImgObj.ATTRS = {
431
* HTML DOM id of the image element.
441
* Background URL for the image.
442
* For an image whose URL is specified by "<code>background-image</code>" in the element's style.
451
* Source URL for the image.
452
* For an image whose URL is specified by a "<code>src</code>" attribute in the DOM element.
461
* Pixel width of the image. Will be set as a <code>width</code> attribute on the DOM element after the image is fetched.
462
* Defaults to the natural width of the image (no <code>width</code> attribute will be set).
463
* Usually only used with src images.
472
* Pixel height of the image. Will be set as a <code>height</code> attribute on the DOM element after the image is fetched.
473
* Defaults to the natural height of the image (no <code>height</code> attribute will be set).
474
* Usually only used with src images.
483
* Whether the image's <code>style.visibility</code> should be set to <code>visible</code> after the image is fetched.
484
* Used when setting images as <code>visibility:hidden</code> prior to image fetching.
485
* @attribute setVisible
493
* Whether the image is a PNG.
494
* PNG images get special treatment in that the URL is specified through AlphaImageLoader for IE, versions 6 and earlier.
495
* Only used with background images.
504
* AlphaImageLoader <code>sizingMethod</code> property to be set for the image.
505
* Only set if <code>isPng</code> value for this image is set to <code>true</code>.
506
* Defaults to <code>scale</code>.
507
* @attribute sizingMethod
515
* AlphaImageLoader <code>enabled</code> property to be set for the image.
516
* Only set if <code>isPng</code> value for this image is set to <code>true</code>.
517
* Defaults to <code>true</code>.
530
* Initialize all private members needed for the group.
537
* Whether this image has already been fetched.
538
* In the case of fold-conditional groups, images won't be fetched twice.
543
this._fetched = false;
546
* The Node object returned from <code>Y.one</code>, to avoid repeat calls to access the DOM.
554
* The vertical position returned from <code>getY</code>, to avoid repeat calls to access the DOM.
555
* The Y position is checked only for images registered with fold-conditional groups. The position is checked first at page load (domready)
556
* and this caching enhancement assumes that the image's vertical position won't change after that first check.
565
* Displays the image; puts the URL into the DOM.
566
* This method shouldn't be called externally, but is not private in the rare event that it needs to be called immediately.
568
* @param {Int} withinY The pixel distance from the top of the page, for which if the image lies within, it will be fetched. Undefined indicates that no check should be made, and the image should always be fetched
569
* @return {Boolean} Whether the image has been fetched (either during this execution or previously)
571
fetch: function(withinY) {
576
var el = this._getImgEl(),
583
// need a distance check
584
yPos = this._getYPos();
585
if (! yPos || yPos > withinY) {
592
if (this.get('bgUrl') !== null) {
594
if (this.get('isPng') && Y.UA.ie && Y.UA.ie <= 6) {
595
// png for which to apply AlphaImageLoader
596
el.setStyle('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + this.get('bgUrl') + '", sizingMethod="' + this.get('sizingMethod') + '", enabled="' + this.get('enabled') + '")');
600
el.setStyle('backgroundImage', "url('" + this.get('bgUrl') + "')");
603
else if (this.get('srcUrl') !== null) {
605
el.setAttribute('src', this.get('srcUrl'));
609
if (this.get('setVisible')) {
610
el.setStyle('visibility', 'visible');
612
if (this.get('width')) {
613
el.setAttribute('width', this.get('width'));
615
if (this.get('height')) {
616
el.setAttribute('height', this.get('height'));
619
this._fetched = true;
625
* Gets the object (as a <code>Y.Node</code>) of the DOM element indicated by "<code>domId</code>".
627
* @returns {Object} DOM element of the image as a <code>Y.Node</code> object
630
_getImgEl: function() {
631
if (this._imgEl === null) {
632
this._imgEl = Y.one('#' + this.get('domId'));
638
* Gets the Y position of the node in page coordinates.
639
* Expects that the page-coordinate position of the image won't change.
641
* @returns {Object} The Y position of the image
644
_getYPos: function() {
645
if (this._yPos === null) {
646
this._yPos = this._getImgEl().getY();
654
Y.extend(Y.ImgLoadImgObj, Y.Base, imgProto);
659
}, '3.4.1' ,{requires:['base-base', 'node-style', 'node-screen']});