lazyLoadableYLT.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * Analyzes images and detects which one can be lazy-loaded (are below the fold)
  3. *
  4. * @see https://github.com/macbre/phantomas/issues/494
  5. */
  6. /* global document: true, window: true */
  7. exports.version = '1.0.a';
  8. exports.module = function(phantomas) {
  9. 'use strict';
  10. phantomas.setMetric('lazyLoadableImagesBelowTheFold'); // @desc number of images displayed below the fold that can be lazy-loaded
  11. phantomas.on('report', function() {
  12. phantomas.log('lazyLoadableImages: analyzing which images can be lazy-loaded...');
  13. phantomas.evaluate(function() {
  14. (function(phantomas) {
  15. phantomas.spyEnabled(false, 'analyzing which images can be lazy-loaded');
  16. var images = document.body.getElementsByTagName('img'),
  17. i,
  18. len = images.length,
  19. offset,
  20. path,
  21. processedImages = {},
  22. src,
  23. viewportHeight = window.innerHeight;
  24. phantomas.log('lazyLoadableImages: %d image(s) found, assuming %dpx offset to be the fold', len, viewportHeight);
  25. for (i = 0; i < len; i++) {
  26. // @see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
  27. offset = images[i].getBoundingClientRect().top;
  28. src = images[i].src;
  29. // ignore base64-encoded images
  30. if (src === '' || /^data:/.test(src)) {
  31. continue;
  32. }
  33. path = phantomas.getDOMPath(images[i]);
  34. // get the most top position for a given image (deduplicate by src)
  35. if (typeof processedImages[src] === 'undefined') {
  36. processedImages[src] = {
  37. offset: offset,
  38. path: path
  39. };
  40. }
  41. // maybe there's the same image loaded above the fold?
  42. if (offset < processedImages[src].offset) {
  43. processedImages[src] = {
  44. offset: offset,
  45. path: path
  46. };
  47. }
  48. }
  49. phantomas.log('lazyLoadableImages: checking %d unique image(s)', Object.keys(processedImages).length);
  50. Object.keys(processedImages).forEach(function(src) {
  51. var img = processedImages[src];
  52. if (img.offset > viewportHeight) {
  53. phantomas.log('lazyLoadableImages: <%s> image (%s) is below the fold (at %dpx)', src, img.path, img.offset);
  54. phantomas.incrMetric('lazyLoadableImagesBelowTheFold');
  55. phantomas.addOffender('lazyLoadableImagesBelowTheFold', src);
  56. }
  57. });
  58. phantomas.spyEnabled(true);
  59. })(window.__phantomas);
  60. });
  61. });
  62. };