Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

imageloader.js 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. /*
  2. Copyright (c) 2010, Yahoo! Inc. All rights reserved.
  3. Code licensed under the BSD License:
  4. http://developer.yahoo.com/yui/license.html
  5. version: 3.4.0
  6. build: nightly
  7. */
  8. YUI.add('imageloader', function(Y) {
  9. /**
  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.
  12. *
  13. * @module imageloader
  14. */
  15. /**
  16. * 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.
  17. * @class ImgLoadGroup
  18. * @extends Base
  19. * @constructor
  20. */
  21. Y.ImgLoadGroup = function() {
  22. // call init first, because it sets up local vars for storing attribute-related info
  23. this._init();
  24. Y.ImgLoadGroup.superclass.constructor.apply(this, arguments);
  25. };
  26. Y.ImgLoadGroup.NAME = 'imgLoadGroup';
  27. Y.ImgLoadGroup.ATTRS = {
  28. /**
  29. * Name for the group. Only used to identify the group in logging statements.
  30. * @attribute name
  31. * @type String
  32. */
  33. name: {
  34. value: ''
  35. },
  36. /**
  37. * Time limit, in seconds, after which images are fetched regardless of trigger events.
  38. * @attribute timeLimit
  39. * @type Number
  40. */
  41. timeLimit: {
  42. value: null
  43. },
  44. /**
  45. * 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.
  46. * This check is performed at page load (domready) and after any window scroll or window resize event (until all images are loaded).
  47. * @attribute foldDistance
  48. * @type Number
  49. */
  50. foldDistance: {
  51. validator: Y.Lang.isNumber,
  52. setter: function(val) { this._setFoldTriggers(); return val; },
  53. lazyAdd: false
  54. },
  55. /**
  56. * Class name that will identify images belonging to the group. This class name will be removed from each element in order to fetch images.
  57. * This class should have, in its CSS style definition, "<code>background:none !important;</code>".
  58. * @attribute className
  59. * @type String
  60. */
  61. className: {
  62. value: null,
  63. setter: function(name) { this._className = name; return name; },
  64. lazyAdd: false
  65. },
  66. /**
  67. * Determines how to act when className is used as the way to delay load images. The "default" action is to just
  68. * remove the class name. The "enhanced" action is to remove the class name and also set the src attribute if
  69. * the element is an img.
  70. * @attribute classNameAction
  71. * @type String
  72. */
  73. classNameAction: {
  74. value: "default"
  75. }
  76. };
  77. var groupProto = {
  78. /**
  79. * Initialize all private members needed for the group.
  80. * @method _init
  81. * @private
  82. */
  83. _init: function() {
  84. /**
  85. * Collection of triggers for this group.
  86. * Keeps track of each trigger's event handle, as returned from <code>Y.on</code>.
  87. * @property _triggers
  88. * @private
  89. * @type Array
  90. */
  91. this._triggers = [];
  92. /**
  93. * Collection of images (<code>Y.ImgLoadImgObj</code> objects) registered with this group, keyed by DOM id.
  94. * @property _imgObjs
  95. * @private
  96. * @type Object
  97. */
  98. this._imgObjs = {};
  99. /**
  100. * Timeout object to keep a handle on the time limit.
  101. * @property _timeout
  102. * @private
  103. * @type Object
  104. */
  105. this._timeout = null;
  106. /**
  107. * DOM elements having the class name that is associated with this group.
  108. * 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.
  109. * @property _classImageEls
  110. * @private
  111. * @type Array
  112. */
  113. this._classImageEls = null;
  114. /**
  115. * Keep the CSS class name in a member variable for ease and speed.
  116. * @property _className
  117. * @private
  118. * @type String
  119. */
  120. this._className = null;
  121. /**
  122. * Boolean tracking whether the window scroll and window resize triggers have been set if this is a fold group.
  123. * @property _areFoldTriggersSet
  124. * @private
  125. * @type Boolean
  126. */
  127. this._areFoldTriggersSet = false;
  128. /**
  129. * The maximum pixel height of the document that has been made visible.
  130. * During fold checks, if the user scrolls up then there's no need to check for newly exposed images.
  131. * @property _maxKnownHLimit
  132. * @private
  133. * @type Int
  134. */
  135. this._maxKnownHLimit = 0;
  136. // add a listener To Domready that will start the time limit
  137. Y.on('domready', this._onloadTasks, this);
  138. },
  139. /**
  140. * Adds a trigger to the group. Arguments are passed to <code>Y.on</code>.
  141. * @method addTrigger
  142. * @chainable
  143. * @param {Object} obj The DOM object to attach the trigger event to
  144. * @param {String} type The event type
  145. */
  146. addTrigger: function(obj, type) {
  147. if (! obj || ! type) {
  148. return this;
  149. }
  150. /* Need to wrap the fetch function. Event Util can't distinguish prototyped functions of different instantiations.
  151. * Leads to this scenario: groupA and groupZ both have window-scroll triggers. groupZ also has a 2-sec timeout (groupA has no timeout).
  152. * 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.
  153. * groupA's trigger is removed and never fires, leaving images unfetched.
  154. */
  155. var wrappedFetch = function() {
  156. this.fetch();
  157. };
  158. this._triggers.push( Y.on(type, wrappedFetch, obj, this) );
  159. return this;
  160. },
  161. /**
  162. * Adds a custom event trigger to the group.
  163. * @method addCustomTrigger
  164. * @chainable
  165. * @param {String} name The name of the event
  166. * @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
  167. */
  168. addCustomTrigger: function(name, obj) {
  169. if (! name) {
  170. return this;
  171. }
  172. // see comment in addTrigger()
  173. var wrappedFetch = function() {
  174. this.fetch();
  175. };
  176. if (Y.Lang.isUndefined(obj)) {
  177. this._triggers.push( Y.on(name, wrappedFetch, this) );
  178. }
  179. else {
  180. this._triggers.push( obj.on(name, wrappedFetch, this) );
  181. }
  182. return this;
  183. },
  184. /**
  185. * Sets the window scroll and window resize triggers for any group that is fold-conditional (i.e., has a fold distance set).
  186. * @method _setFoldTriggers
  187. * @private
  188. */
  189. _setFoldTriggers: function() {
  190. if (this._areFoldTriggersSet) {
  191. return;
  192. }
  193. var wrappedFoldCheck = function() {
  194. this._foldCheck();
  195. };
  196. this._triggers.push( Y.on('scroll', wrappedFoldCheck, window, this) );
  197. this._triggers.push( Y.on('resize', wrappedFoldCheck, window, this) );
  198. this._areFoldTriggersSet = true;
  199. },
  200. /**
  201. * Performs necessary setup at domready time.
  202. * Initiates time limit for group; executes the fold check for the images.
  203. * @method _onloadTasks
  204. * @private
  205. */
  206. _onloadTasks: function() {
  207. var timeLim = this.get('timeLimit');
  208. if (timeLim && timeLim > 0) {
  209. this._timeout = setTimeout(this._getFetchTimeout(), timeLim * 1000);
  210. }
  211. if (! Y.Lang.isUndefined(this.get('foldDistance'))) {
  212. this._foldCheck();
  213. }
  214. },
  215. /**
  216. * Returns the group's <code>fetch</code> method, with the proper closure, for use with <code>setTimeout</code>.
  217. * @method _getFetchTimeout
  218. * @return {Function} group's <code>fetch</code> method
  219. * @private
  220. */
  221. _getFetchTimeout: function() {
  222. var self = this;
  223. return function() { self.fetch(); };
  224. },
  225. /**
  226. * Registers an image with the group.
  227. * 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.
  228. * @method registerImage
  229. * @param {Object} * A configuration object literal with attribute name/value pairs (passed through to a <code>Y.ImgLoadImgObj</code> constructor)
  230. * @return {Object} <code>Y.ImgLoadImgObj</code> that was registered
  231. */
  232. registerImage: function() {
  233. var domId = arguments[0].domId;
  234. if (! domId) {
  235. return null;
  236. }
  237. this._imgObjs[domId] = new Y.ImgLoadImgObj(arguments[0]);
  238. return this._imgObjs[domId];
  239. },
  240. /**
  241. * Displays the images in the group.
  242. * 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.
  243. * @method fetch
  244. */
  245. fetch: function() {
  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. var allFetched = true,
  276. viewReg = Y.DOM.viewportRegion(),
  277. hLimit = viewReg.bottom + this.get('foldDistance'),
  278. id, imgFetched, els, i, len;
  279. // unless we've uncovered new frontiers, there's no need to continue
  280. if (hLimit <= this._maxKnownHLimit) {
  281. return;
  282. }
  283. this._maxKnownHLimit = hLimit;
  284. for (id in this._imgObjs) {
  285. if (this._imgObjs.hasOwnProperty(id)) {
  286. imgFetched = this._imgObjs[id].fetch(hLimit);
  287. allFetched = allFetched && imgFetched;
  288. }
  289. }
  290. // and by class
  291. if (this._className) {
  292. if (this._classImageEls === null) {
  293. // get all the relevant elements and store them
  294. this._classImageEls = [];
  295. els = Y.all('.' + this._className);
  296. els.each( function(node) { this._classImageEls.push( { el: node, y: node.getY(), fetched: false } ); }, this);
  297. }
  298. els = this._classImageEls;
  299. for (i=0, len = els.length; i < len; i++) {
  300. if (els[i].fetched) {
  301. continue;
  302. }
  303. if (els[i].y && els[i].y <= hLimit) {
  304. //els[i].el.removeClass(this._className);
  305. this._updateNodeClassName(els[i].el);
  306. els[i].fetched = true;
  307. }
  308. else {
  309. allFetched = false;
  310. }
  311. }
  312. }
  313. // if allFetched, remove listeners
  314. if (allFetched) {
  315. this._clearTriggers();
  316. }
  317. },
  318. /**
  319. * Updates a given node, removing the ImageLoader class name. If the
  320. * node is an img and the classNameAction is "enhanced", then node
  321. * class name is removed and also the src attribute is set to the
  322. * image URL as well as clearing the style background image.
  323. * @method _updateNodeClassName
  324. * @param node {Node} The node to act on.
  325. * @private
  326. */
  327. _updateNodeClassName: function(node){
  328. var url;
  329. if (this.get("classNameAction") == "enhanced"){
  330. if (node.get("tagName").toLowerCase() == "img"){
  331. url = node.getStyle("backgroundImage");
  332. /url\(["']?(.*?)["']?\)/.test(url);
  333. url = RegExp.$1;
  334. node.set("src", url);
  335. node.setStyle("backgroundImage", "");
  336. }
  337. }
  338. node.removeClass(this._className);
  339. },
  340. /**
  341. * 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.
  342. * @method _fetchByClass
  343. * @private
  344. */
  345. _fetchByClass: function() {
  346. if (! this._className) {
  347. return;
  348. }
  349. Y.all('.' + this._className).each(Y.bind(this._updateNodeClassName, this));
  350. }
  351. };
  352. Y.extend(Y.ImgLoadGroup, Y.Base, groupProto);
  353. //------------------------------------------------
  354. /**
  355. * Image objects to be registered with the groups
  356. * @class ImgLoadImgObj
  357. * @extends Base
  358. * @constructor
  359. */
  360. Y.ImgLoadImgObj = function() {
  361. Y.ImgLoadImgObj.superclass.constructor.apply(this, arguments);
  362. this._init();
  363. };
  364. Y.ImgLoadImgObj.NAME = 'imgLoadImgObj';
  365. Y.ImgLoadImgObj.ATTRS = {
  366. /**
  367. * HTML DOM id of the image element.
  368. * @attribute domId
  369. * @type String
  370. */
  371. domId: {
  372. value: null,
  373. writeOnce: true
  374. },
  375. /**
  376. * Background URL for the image.
  377. * For an image whose URL is specified by "<code>background-image</code>" in the element's style.
  378. * @attribute bgUrl
  379. * @type String
  380. */
  381. bgUrl: {
  382. value: null
  383. },
  384. /**
  385. * Source URL for the image.
  386. * For an image whose URL is specified by a "<code>src</code>" attribute in the DOM element.
  387. * @attribute srcUrl
  388. * @type String
  389. */
  390. srcUrl: {
  391. value: null
  392. },
  393. /**
  394. * Pixel width of the image. Will be set as a <code>width</code> attribute on the DOM element after the image is fetched.
  395. * Defaults to the natural width of the image (no <code>width</code> attribute will be set).
  396. * Usually only used with src images.
  397. * @attribute width
  398. * @type Int
  399. */
  400. width: {
  401. value: null
  402. },
  403. /**
  404. * Pixel height of the image. Will be set as a <code>height</code> attribute on the DOM element after the image is fetched.
  405. * Defaults to the natural height of the image (no <code>height</code> attribute will be set).
  406. * Usually only used with src images.
  407. * @attribute height
  408. * @type Int
  409. */
  410. height: {
  411. value: null
  412. },
  413. /**
  414. * Whether the image's <code>style.visibility</code> should be set to <code>visible</code> after the image is fetched.
  415. * Used when setting images as <code>visibility:hidden</code> prior to image fetching.
  416. * @attribute setVisible
  417. * @type Boolean
  418. */
  419. setVisible: {
  420. value: false
  421. },
  422. /**
  423. * Whether the image is a PNG.
  424. * PNG images get special treatment in that the URL is specified through AlphaImageLoader for IE, versions 6 and earlier.
  425. * Only used with background images.
  426. * @attribute isPng
  427. * @type Boolean
  428. */
  429. isPng: {
  430. value: false
  431. },
  432. /**
  433. * AlphaImageLoader <code>sizingMethod</code> property to be set for the image.
  434. * Only set if <code>isPng</code> value for this image is set to <code>true</code>.
  435. * Defaults to <code>scale</code>.
  436. * @attribute sizingMethod
  437. * @type String
  438. */
  439. sizingMethod: {
  440. value: 'scale'
  441. },
  442. /**
  443. * AlphaImageLoader <code>enabled</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>true</code>.
  446. * @attribute enabled
  447. * @type String
  448. */
  449. enabled: {
  450. value: 'true'
  451. }
  452. };
  453. var imgProto = {
  454. /**
  455. * Initialize all private members needed for the group.
  456. * @method _init
  457. * @private
  458. */
  459. _init: function() {
  460. /**
  461. * Whether this image has already been fetched.
  462. * In the case of fold-conditional groups, images won't be fetched twice.
  463. * @property _fetched
  464. * @private
  465. * @type Boolean
  466. */
  467. this._fetched = false;
  468. /**
  469. * The Node object returned from <code>Y.one</code>, to avoid repeat calls to access the DOM.
  470. * @property _imgEl
  471. * @private
  472. * @type Object
  473. */
  474. this._imgEl = null;
  475. /**
  476. * The vertical position returned from <code>getY</code>, to avoid repeat calls to access the DOM.
  477. * The Y position is checked only for images registered with fold-conditional groups. The position is checked first at page load (domready)
  478. * and this caching enhancement assumes that the image's vertical position won't change after that first check.
  479. * @property _yPos
  480. * @private
  481. * @type Int
  482. */
  483. this._yPos = null;
  484. },
  485. /**
  486. * Displays the image; puts the URL into the DOM.
  487. * This method shouldn't be called externally, but is not private in the rare event that it needs to be called immediately.
  488. * @method fetch
  489. * @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
  490. * @return {Boolean} Whether the image has been fetched (either during this execution or previously)
  491. */
  492. fetch: function(withinY) {
  493. if (this._fetched) {
  494. return true;
  495. }
  496. var el = this._getImgEl(),
  497. yPos;
  498. if (! el) {
  499. return false;
  500. }
  501. if (withinY) {
  502. // need a distance check
  503. yPos = this._getYPos();
  504. if (! yPos || yPos > withinY) {
  505. return false;
  506. }
  507. }
  508. // apply url
  509. if (this.get('bgUrl') !== null) {
  510. // bg url
  511. if (this.get('isPng') && Y.UA.ie && Y.UA.ie <= 6) {
  512. // png for which to apply AlphaImageLoader
  513. el.setStyle('filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + this.get('bgUrl') + '", sizingMethod="' + this.get('sizingMethod') + '", enabled="' + this.get('enabled') + '")');
  514. }
  515. else {
  516. // regular bg image
  517. el.setStyle('backgroundImage', "url('" + this.get('bgUrl') + "')");
  518. }
  519. }
  520. else if (this.get('srcUrl') !== null) {
  521. // regular src image
  522. el.setAttribute('src', this.get('srcUrl'));
  523. }
  524. // apply attributes
  525. if (this.get('setVisible')) {
  526. el.setStyle('visibility', 'visible');
  527. }
  528. if (this.get('width')) {
  529. el.setAttribute('width', this.get('width'));
  530. }
  531. if (this.get('height')) {
  532. el.setAttribute('height', this.get('height'));
  533. }
  534. this._fetched = true;
  535. return true;
  536. },
  537. /**
  538. * Gets the object (as a <code>Y.Node</code>) of the DOM element indicated by "<code>domId</code>".
  539. * @method _getImgEl
  540. * @returns {Object} DOM element of the image as a <code>Y.Node</code> object
  541. * @private
  542. */
  543. _getImgEl: function() {
  544. if (this._imgEl === null) {
  545. this._imgEl = Y.one('#' + this.get('domId'));
  546. }
  547. return this._imgEl;
  548. },
  549. /**
  550. * Gets the Y position of the node in page coordinates.
  551. * Expects that the page-coordinate position of the image won't change.
  552. * @method _getYPos
  553. * @returns {Object} The Y position of the image
  554. * @private
  555. */
  556. _getYPos: function() {
  557. if (this._yPos === null) {
  558. this._yPos = this._getImgEl().getY();
  559. }
  560. return this._yPos;
  561. }
  562. };
  563. Y.extend(Y.ImgLoadImgObj, Y.Base, imgProto);
  564. }, '3.4.0' ,{requires:['base-base', 'node-style', 'node-screen']});