API Docs for: 3.8.0
Show:

File: imageloader/js/imageloader.js

  1. /**
  2.  * The ImageLoader Utility is a framework to dynamically load images according to certain triggers,
  3.  * enabling faster load times and a more responsive UI.
  4.  *
  5.  * @module imageloader
  6.  */


  7.         /**
  8.          * 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.
  9.          * @class ImgLoadGroup
  10.          * @extends Base
  11.          * @constructor
  12.          */
  13.         Y.ImgLoadGroup = function() {
  14.                 // call init first, because it sets up local vars for storing attribute-related info
  15.                 this._init();
  16.                 Y.ImgLoadGroup.superclass.constructor.apply(this, arguments);
  17.         };

  18.         Y.ImgLoadGroup.NAME = 'imgLoadGroup';

  19.         Y.ImgLoadGroup.ATTRS = {
  20.                
  21.                 /**
  22.                  * Name for the group. Only used to identify the group in logging statements.
  23.                  * @attribute name
  24.                  * @type String
  25.                  */
  26.                 name: {
  27.                         value: ''
  28.                 },

  29.                 /**
  30.                  * Time limit, in seconds, after which images are fetched regardless of trigger events.
  31.                  * @attribute timeLimit
  32.                  * @type Number
  33.                  */
  34.                 timeLimit: {
  35.                         value: null
  36.                 },

  37.                 /**
  38.                  * 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.
  39.                  * This check is performed at page load (domready) and after any window scroll or window resize event (until all images are loaded).
  40.                  * @attribute foldDistance
  41.                  * @type Number
  42.                  */
  43.                 foldDistance: {
  44.                         validator: Y.Lang.isNumber,
  45.                         setter: function(val) { this._setFoldTriggers(); return val; },
  46.                         lazyAdd: false
  47.                 },

  48.                 /**
  49.                  * Class name that will identify images belonging to the group. This class name will be removed from each element in order to fetch images.
  50.                  * This class should have, in its CSS style definition, "<code>background:none !important;</code>".
  51.                  * @attribute className
  52.                  * @type String
  53.                  */
  54.                 className: {
  55.                         value: null,
  56.                         setter: function(name) { this._className = name; return name; },
  57.                         lazyAdd: false
  58.                 },
  59.        
  60.         /**
  61.          * Determines how to act when className is used as the way to delay load images. The "default" action is to just
  62.          * remove the class name. The "enhanced" action is to remove the class name and also set the src attribute if
  63.          * the element is an img.
  64.          * @attribute classNameAction
  65.          * @type String
  66.          */
  67.         classNameAction: {
  68.             value: "default"
  69.         }

  70.         };

  71.         var groupProto = {

  72.                 /**
  73.                  * Initialize all private members needed for the group.
  74.                  * @method _init
  75.                  * @private
  76.                  */
  77.                 _init: function() {

  78.                         /**
  79.                          * Collection of triggers for this group.
  80.                          * Keeps track of each trigger's event handle, as returned from <code>Y.on</code>.
  81.                          * @property _triggers
  82.                          * @private
  83.                          * @type Array
  84.                          */
  85.                         this._triggers = [];

  86.                         /**
  87.                          * Collection of images (<code>Y.ImgLoadImgObj</code> objects) registered with this group, keyed by DOM id.
  88.                          * @property _imgObjs
  89.                          * @private
  90.                          * @type Object
  91.                          */
  92.                         this._imgObjs = {};

  93.                         /**
  94.                          * Timeout object to keep a handle on the time limit.
  95.                          * @property _timeout
  96.                          * @private
  97.                          * @type Object
  98.                          */
  99.                         this._timeout = null;

  100.                         /**
  101.                          * DOM elements having the class name that is associated with this group.
  102.                          * 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.
  103.                          * @property _classImageEls
  104.                          * @private
  105.                          * @type Array
  106.                          */
  107.                         this._classImageEls = null;

  108.                         /**
  109.                          * Keep the CSS class name in a member variable for ease and speed.
  110.                          * @property _className
  111.                          * @private
  112.                          * @type String
  113.                          */
  114.                         this._className = null;

  115.                         /**
  116.                          * Boolean tracking whether the window scroll and window resize triggers have been set if this is a fold group.
  117.                          * @property _areFoldTriggersSet
  118.                          * @private
  119.                          * @type Boolean
  120.                          */
  121.                         this._areFoldTriggersSet = false;

  122.                         /**
  123.                          * The maximum pixel height of the document that has been made visible.
  124.                          * During fold checks, if the user scrolls up then there's no need to check for newly exposed images.
  125.                          * @property _maxKnownHLimit
  126.                          * @private
  127.                          * @type Int
  128.                          */
  129.                         this._maxKnownHLimit = 0;

  130.                         // add a listener to domready that will start the time limit
  131.                         Y.on('domready', this._onloadTasks, this);
  132.                 },

  133.                 /**
  134.                  * Adds a trigger to the group. Arguments are passed to <code>Y.on</code>.
  135.                  * @method addTrigger
  136.                  * @chainable
  137.                  * @param {Object} obj  The DOM object to attach the trigger event to
  138.                  * @param {String} type  The event type
  139.                  */
  140.                 addTrigger: function(obj, type) {
  141.                         if (! obj || ! type) {
  142.                                 return this;
  143.                         }

  144.                         Y.log('adding trigger to group: ' + this.get('name'), 'info', 'imageloader');

  145.                         /* Need to wrap the fetch function. Event Util can't distinguish prototyped functions of different instantiations.
  146.                          *   Leads to this scenario: groupA and groupZ both have window-scroll triggers. groupZ also has a 2-sec timeout (groupA has no timeout).
  147.                          *   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.
  148.                          *   groupA's trigger is removed and never fires, leaving images unfetched.
  149.                          */
  150.                         var wrappedFetch = function() {
  151.                                 this.fetch();
  152.                         };
  153.                         this._triggers.push( Y.on(type, wrappedFetch, obj, this) );

  154.                         return this;
  155.                 },

  156.                 /**
  157.                  * Adds a custom event trigger to the group.
  158.                  * @method addCustomTrigger
  159.                  * @chainable
  160.                  * @param {String} name  The name of the event
  161.                  * @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
  162.                  */
  163.                 addCustomTrigger: function(name, obj) {
  164.                         if (! name) {
  165.                                 return this;
  166.                         }

  167.                         Y.log('adding custom trigger to group: ' + this.get('name'), 'info', 'imageloader');

  168.                         // see comment in addTrigger()
  169.                         var wrappedFetch = function() {
  170.                                 this.fetch();
  171.                         };
  172.                         if (Y.Lang.isUndefined(obj)) {
  173.                                 this._triggers.push( Y.on(name, wrappedFetch, this) );
  174.                         }
  175.                         else {
  176.                                 this._triggers.push( obj.on(name, wrappedFetch, this) );
  177.                         }

  178.                         return this;
  179.                 },

  180.                 /**
  181.                  * Sets the window scroll and window resize triggers for any group that is fold-conditional (i.e., has a fold distance set).
  182.                  * @method _setFoldTriggers
  183.                  * @private
  184.                  */
  185.                 _setFoldTriggers: function() {
  186.                         if (this._areFoldTriggersSet) {
  187.                                 return;
  188.                         }

  189.                         Y.log('setting window scroll and resize events for group: ' + this.get('name'), 'info', 'imageloader');

  190.                         var wrappedFoldCheck = function() {
  191.                                 this._foldCheck();
  192.                         };
  193.                         this._triggers.push( Y.on('scroll', wrappedFoldCheck, window, this) );
  194.                         this._triggers.push( Y.on('resize', wrappedFoldCheck, window, this) );
  195.                         this._areFoldTriggersSet = true;
  196.                 },

  197.                 /**
  198.                  * Performs necessary setup at domready time.
  199.                  * Initiates time limit for group; executes the fold check for the images.
  200.                  * @method _onloadTasks
  201.                  * @private
  202.                  */
  203.                 _onloadTasks: function() {
  204.                         var timeLim = this.get('timeLimit');
  205.                         if (timeLim && timeLim > 0) {
  206.                                 Y.log('setting time limit of ' + timeLim + ' seconds for group: ' + this.get('name'), 'info', 'imageloader');
  207.                                 this._timeout = setTimeout(this._getFetchTimeout(), timeLim * 1000);
  208.                         }

  209.                         if (! Y.Lang.isUndefined(this.get('foldDistance'))) {
  210.                                 this._foldCheck();
  211.                         }
  212.                 },

  213.                 /**
  214.                  * Returns the group's <code>fetch</code> method, with the proper closure, for use with <code>setTimeout</code>.
  215.                  * @method _getFetchTimeout
  216.                  * @return {Function}  group's <code>fetch</code> method
  217.                  * @private
  218.                  */
  219.                 _getFetchTimeout: function() {
  220.                         var self = this;
  221.                         return function() { self.fetch(); };
  222.                 },

  223.                 /**
  224.                  * Registers an image with the group.
  225.                  * 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.
  226.                  * @method registerImage
  227.                  * @param {Object} *  A configuration object literal with attribute name/value pairs  (passed through to a <code>Y.ImgLoadImgObj</code> constructor)
  228.                  * @return {Object}  <code>Y.ImgLoadImgObj</code> that was registered
  229.                  */
  230.                 registerImage: function() {
  231.                         var domId = arguments[0].domId;
  232.                         if (! domId) {
  233.                                 return null;
  234.                         }

  235.                         Y.log('adding image with id: ' + domId + ' to group: ' + this.get('name'), 'info', 'imageloader');

  236.                         this._imgObjs[domId] = new Y.ImgLoadImgObj(arguments[0]);
  237.                         return this._imgObjs[domId];
  238.                 },

  239.                 /**
  240.                  * Displays the images in the group.
  241.                  * 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.
  242.                  * @method fetch
  243.                  */
  244.                 fetch: function() {
  245.                         Y.log('Fetching images in group: "' + this.get('name') + '".', 'info', 'imageloader');

  246.                         // done with the triggers
  247.                         this._clearTriggers();

  248.                         // fetch whatever we need to by className
  249.                         this._fetchByClass();

  250.                         // fetch registered images
  251.                         for (var id in this._imgObjs) {
  252.                                 if (this._imgObjs.hasOwnProperty(id)) {
  253.                                         this._imgObjs[id].fetch();
  254.                                 }
  255.                         }
  256.                 },

  257.                 /**
  258.                  * Clears the timeout and all triggers associated with the group.
  259.                  * @method _clearTriggers
  260.                  * @private
  261.                  */
  262.                 _clearTriggers: function() {
  263.                         clearTimeout(this._timeout);
  264.                         // detach all listeners
  265.                         for (var i=0, len = this._triggers.length; i < len; i++) {
  266.                                 this._triggers[i].detach();
  267.                         }
  268.                 },

  269.                 /**
  270.                  * 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.
  271.                  * @method _foldCheck
  272.                  * @private
  273.                  */
  274.                 _foldCheck: function() {
  275.                         Y.log('Checking for images above the fold in group: "' + this.get('name') + '"', 'info', 'imageloader');

  276.                         var allFetched = true,
  277.                             viewReg = Y.DOM.viewportRegion(),
  278.                             hLimit = viewReg.bottom + this.get('foldDistance'),
  279.                                         id, imgFetched, els, i, len;

  280.                         // unless we've uncovered new frontiers, there's no need to continue
  281.                         if (hLimit <= this._maxKnownHLimit) {
  282.                                 return;
  283.                         }
  284.                         this._maxKnownHLimit = hLimit;

  285.                         for (id in this._imgObjs) {
  286.                                 if (this._imgObjs.hasOwnProperty(id)) {
  287.                                         imgFetched = this._imgObjs[id].fetch(hLimit);
  288.                                         allFetched = allFetched && imgFetched;
  289.                                 }
  290.                         }

  291.                         // and by class
  292.                         if (this._className) {
  293.                                 if (this._classImageEls === null) {
  294.                                         // get all the relevant elements and store them
  295.                                         this._classImageEls = [];
  296.                                         els = Y.all('.' + this._className);
  297.                                         els.each( function(node) { this._classImageEls.push( { el: node, y: node.getY(), fetched: false } ); }, this);
  298.                                 }
  299.                                 els = this._classImageEls;
  300.                                 for (i=0, len = els.length; i < len; i++) {
  301.                                         if (els[i].fetched) {
  302.                                                 continue;
  303.                                         }
  304.                                         if (els[i].y && els[i].y <= hLimit) {
  305.                                                 //els[i].el.removeClass(this._className);
  306.                                                 this._updateNodeClassName(els[i].el);
  307.                         els[i].fetched = true;
  308.                                                 Y.log('Image with id "' + els[i].el.get('id') + '" is within distance of the fold. Fetching image. (Image registered by class name with the group - may not have an id.)', 'info', 'imageloader');
  309.                                         }
  310.                                         else {
  311.                                                 allFetched = false;
  312.                                         }
  313.                                 }
  314.                         }
  315.                        
  316.                         // if allFetched, remove listeners
  317.                         if (allFetched) {
  318.                                 Y.log('All images fetched; removing listeners for group: "' + this.get('name') + '"', 'info', 'imageloader');
  319.                                 this._clearTriggers();
  320.                         }
  321.                 },
  322.        
  323.         /**
  324.          * Updates a given node, removing the ImageLoader class name. If the
  325.          * node is an img and the classNameAction is "enhanced", then node
  326.          * class name is removed and also the src attribute is set to the
  327.          * image URL as well as clearing the style background image.
  328.          * @method _updateNodeClassName
  329.          * @param node {Node} The node to act on.
  330.          * @private
  331.          */
  332.         _updateNodeClassName: function(node){
  333.             var url;
  334.            
  335.             if (this.get("classNameAction") == "enhanced"){
  336.                
  337.                 if (node.get("tagName").toLowerCase() == "img"){
  338.                     url = node.getStyle("backgroundImage");
  339.                     /url\(["']?(.*?)["']?\)/.test(url);
  340.                     url = RegExp.$1;
  341.                     node.set("src", url);
  342.                     node.setStyle("backgroundImage", "");
  343.                 }
  344.             }
  345.            
  346.             node.removeClass(this._className);        
  347.         },

  348.                 /**
  349.                  * 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.
  350.                  * @method _fetchByClass
  351.                  * @private
  352.                  */
  353.                 _fetchByClass: function() {
  354.                         if (! this._className) {
  355.                                 return;
  356.                         }

  357.                         Y.log('Fetching all images with class "' + this._className + '" in group "' + this.get('name') + '".', 'info', 'imageloader');

  358.                         Y.all('.' + this._className).each(Y.bind(this._updateNodeClassName, this));
  359.                 }

  360.         };


  361.         Y.extend(Y.ImgLoadGroup, Y.Base, groupProto);


  362.         //------------------------------------------------


  363.         /**
  364.          * Image objects to be registered with the groups
  365.          * @class ImgLoadImgObj
  366.          * @extends Base
  367.          * @constructor
  368.          */
  369.         Y.ImgLoadImgObj = function() {
  370.                 Y.ImgLoadImgObj.superclass.constructor.apply(this, arguments);
  371.                 this._init();
  372.         };
  373.                
  374.         Y.ImgLoadImgObj.NAME = 'imgLoadImgObj';

  375.         Y.ImgLoadImgObj.ATTRS = {
  376.                 /**
  377.                  * HTML DOM id of the image element.
  378.                  * @attribute domId
  379.                  * @type String
  380.                  */
  381.                 domId: {
  382.                         value: null,
  383.                         writeOnce: true
  384.                 },

  385.                 /**
  386.                  * Background URL for the image.
  387.                  * For an image whose URL is specified by "<code>background-image</code>" in the element's style.
  388.                  * @attribute bgUrl
  389.                  * @type String
  390.                  */
  391.                 bgUrl: {
  392.                         value: null
  393.                 },

  394.                 /**
  395.                  * Source URL for the image.
  396.                  * For an image whose URL is specified by a "<code>src</code>" attribute in the DOM element.
  397.                  * @attribute srcUrl
  398.                  * @type String
  399.                  */
  400.                 srcUrl: {
  401.                         value: null
  402.                 },

  403.                 /**
  404.                  * Pixel width of the image. Will be set as a <code>width</code> attribute on the DOM element after the image is fetched.
  405.                  * Defaults to the natural width of the image (no <code>width</code> attribute will be set).
  406.                  * Usually only used with src images.
  407.                  * @attribute width
  408.                  * @type Int
  409.                  */
  410.                 width: {
  411.                         value: null
  412.                 },

  413.                 /**
  414.                  * Pixel height of the image. Will be set as a <code>height</code> attribute on the DOM element after the image is fetched.
  415.                  * Defaults to the natural height of the image (no <code>height</code> attribute will be set).
  416.                  * Usually only used with src images.
  417.                  * @attribute height
  418.                  * @type Int
  419.                  */
  420.                 height: {
  421.                         value: null
  422.                 },

  423.                 /**
  424.                  * Whether the image's <code>style.visibility</code> should be set to <code>visible</code> after the image is fetched.
  425.                  * Used when setting images as <code>visibility:hidden</code> prior to image fetching.
  426.                  * @attribute setVisible
  427.                  * @type Boolean
  428.                  */
  429.                 setVisible: {
  430.                         value: false
  431.                 },

  432.                 /**
  433.                  * Whether the image is a PNG.
  434.                  * PNG images get special treatment in that the URL is specified through AlphaImageLoader for IE, versions 6 and earlier.
  435.                  * Only used with background images.
  436.                  * @attribute isPng
  437.                  * @type Boolean
  438.                  */
  439.                 isPng: {
  440.                         value: false
  441.                 },

  442.                 /**
  443.                  * AlphaImageLoader <code>sizingMethod</code> property to be set for the image.
  444.                  * Only set if <code>isPng</code> value for this image is set to <code>true</code>.
  445.                  * Defaults to <code>scale</code>.
  446.                  * @attribute sizingMethod
  447.                  * @type String
  448.                  */
  449.                 sizingMethod: {
  450.                         value: 'scale'
  451.                 },

  452.                 /**
  453.                  * AlphaImageLoader <code>enabled</code> property to be set for the image.
  454.                  * Only set if <code>isPng</code> value for this image is set to <code>true</code>.
  455.                  * Defaults to <code>true</code>.
  456.                  * @attribute enabled
  457.                  * @type String
  458.                  */
  459.                 enabled: {
  460.                         value: 'true'
  461.                 }

  462.         };

  463.         var imgProto = {

  464.                 /**
  465.                  * Initialize all private members needed for the group.
  466.                  * @method _init
  467.                  * @private
  468.                  */
  469.                 _init: function() {

  470.                         /**
  471.                          * Whether this image has already been fetched.
  472.                          * In the case of fold-conditional groups, images won't be fetched twice.
  473.                          * @property _fetched
  474.                          * @private
  475.                          * @type Boolean
  476.                          */
  477.                         this._fetched = false;

  478.                         /**
  479.                          * The Node object returned from <code>Y.one</code>, to avoid repeat calls to access the DOM.
  480.                          * @property _imgEl
  481.                          * @private
  482.                          * @type Object
  483.                          */
  484.                         this._imgEl = null;

  485.                         /**
  486.                          * The vertical position returned from <code>getY</code>, to avoid repeat calls to access the DOM.
  487.                          * The Y position is checked only for images registered with fold-conditional groups. The position is checked first at page load (domready)
  488.                          *   and this caching enhancement assumes that the image's vertical position won't change after that first check.
  489.                          * @property _yPos
  490.                          * @private
  491.                          * @type Int
  492.                          */
  493.                         this._yPos = null;
  494.                 },

  495.                 /**
  496.                  * Displays the image; puts the URL into the DOM.
  497.                  * This method shouldn't be called externally, but is not private in the rare event that it needs to be called immediately.
  498.                  * @method fetch
  499.                  * @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
  500.                  * @return {Boolean}  Whether the image has been fetched (either during this execution or previously)
  501.                  */
  502.                 fetch: function(withinY) {
  503.                         if (this._fetched) {
  504.                                 return true;
  505.                         }

  506.                         var el = this._getImgEl(),
  507.                             yPos;
  508.                         if (! el) {
  509.                                 return false;
  510.                         }

  511.                         if (withinY) {
  512.                                 // need a distance check
  513.                                 yPos = this._getYPos();
  514.                                 if (! yPos || yPos > withinY) {
  515.                                         return false;
  516.                                 }
  517.                                 Y.log('Image with id "' + this.get('domId') + '" is within distance of the fold. Fetching image.', 'info', 'imageloader');
  518.                         }

  519.                         Y.log('Fetching image with id "' + this.get('domId') + '".', 'info', 'imageloader');

  520.                         // apply url
  521.                         if (this.get('bgUrl') !== null) {
  522.                                 // bg url
  523.                                 if (this.get('isPng') && Y.UA.ie && Y.UA.ie <= 6) {
  524.                                         // png for which to apply AlphaImageLoader
  525.                                         el.setStyle('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + this.get('bgUrl') + '", sizingMethod="' + this.get('sizingMethod') + '", enabled="' + this.get('enabled') + '")');
  526.                                 }
  527.                                 else {
  528.                                         // regular bg image
  529.                                         el.setStyle('backgroundImage', "url('" + this.get('bgUrl') + "')");
  530.                                 }
  531.                         }
  532.                         else if (this.get('srcUrl') !== null) {
  533.                                 // regular src image
  534.                                 el.setAttribute('src', this.get('srcUrl'));
  535.                         }

  536.                         // apply attributes
  537.                         if (this.get('setVisible')) {
  538.                                 el.setStyle('visibility', 'visible');
  539.                         }
  540.                         if (this.get('width')) {
  541.                                 el.setAttribute('width', this.get('width'));
  542.                         }
  543.                         if (this.get('height')) {
  544.                                 el.setAttribute('height', this.get('height'));
  545.                         }

  546.                         this._fetched = true;

  547.                         return true;
  548.                 },

  549.                 /**
  550.                  * Gets the object (as a <code>Y.Node</code>) of the DOM element indicated by "<code>domId</code>".
  551.                  * @method _getImgEl
  552.                  * @returns {Object} DOM element of the image as a <code>Y.Node</code> object
  553.                  * @private
  554.                  */
  555.                 _getImgEl: function() {
  556.                         if (this._imgEl === null) {
  557.                                 this._imgEl = Y.one('#' + this.get('domId'));
  558.                         }
  559.                         return this._imgEl;
  560.                 },

  561.                 /**
  562.                  * Gets the Y position of the node in page coordinates.
  563.                  * Expects that the page-coordinate position of the image won't change.
  564.                  * @method _getYPos
  565.                  * @returns {Object} The Y position of the image
  566.                  * @private
  567.                  */
  568.                 _getYPos: function() {
  569.                         if (this._yPos === null) {
  570.                                 this._yPos = this._getImgEl().getY();
  571.                         }
  572.                         return this._yPos;
  573.                 }

  574.         };


  575.         Y.extend(Y.ImgLoadImgObj, Y.Base, imgProto);



  576.