Progressive Image Loading in JavaScript

Progressive Image Loading in JavaScript
Code Snippet:Pilpil - Progressive Image Loading
Author: MM Aurangajeb
Published: January 20, 2024
Last Updated: January 22, 2024
Downloads: 740
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code implements progressive image loading with a blur effect to enhance page load times. It calculates aspect ratios, sets max dimensions, and loads images progressively. It’s helpful for optimizing image-heavy websites.

You can use this code on image-rich websites to improve loading times. It reduces initial page load delay by loading low-quality images first and then replacing them with high-quality ones, enhancing user experience. This helps retain visitor engagement and improves overall site performance.

How to Use Progressive Image Loading JavaScript Code

1. Inside your HTML container (<div class="container"> in the example), insert the images you want to load progressively using the following structure:

  1. <div class="container">
  2. <figure class="graf-figure">
  3. <div class="aspectRatioPlaceholder">
  4. <div class="aspectRatioPlaceholder-fill"></div>
  5. <div class="progressiveMedia" data-width="YOUR_IMAGE_WIDTH" data-height="YOUR_IMAGE_HEIGHT">
  6. <img class="progressiveMedia-thumbnail" src="LOW_QUALITY_IMAGE_URL" />
  7. <canvas class="progressiveMedia-canvas"></canvas>
  8. <img class="progressiveMedia-image" data-src="HIGH_QUALITY_IMAGE_URL" /> </div>
  9. </div>
  10. </figure>
  11. </div>

Replace YOUR_IMAGE_WIDTH, YOUR_IMAGE_HEIGHT, LOW_QUALITY_IMAGE_URL, and HIGH_QUALITY_IMAGE_URL with the appropriate values and image URLs.

2. Similarly, add the following CSS code to your project to add a blur effect while loading images progressively. You can modify the CSS code (in styles.css) to match your website’s design and layout preferences.

  1. /**
  2. * Pilpil v1.0.0 - Progressive Image Loading
  3. * @link https://zafree.github.io/pilpil
  4. * @copyright 2015-2023 Zafree
  5. * @license MIT
  6. */
  7. figure {
  8. display: block;
  9. margin: 0; }
  10.  
  11. .graf-figure {
  12. position: relative;
  13. clear: both;
  14. outline: 0;
  15. -webkit-box-sizing: border-box;
  16. -moz-box-sizing: border-box;
  17. box-sizing: border-box; }
  18.  
  19. .aspectRatioPlaceholder {
  20. position: relative;
  21. width: 100%;
  22. margin: 0 auto;
  23. display: block; }
  24.  
  25. .aspectRatioPlaceholder-fill {
  26. display: block; }
  27.  
  28. .progressiveMedia {
  29. position: absolute;
  30. top: 0;
  31. left: 0;
  32. width: 100%;
  33. height: 100%;
  34. background: rgba(0, 0, 0, 0.05); }
  35.  
  36. .progressiveMedia-thumbnail {
  37. display: none; }
  38.  
  39. .progressiveMedia-canvas {
  40. display: block;
  41. position: absolute;
  42. top: 0;
  43. left: 0;
  44. width: 100%;
  45. height: 100%;
  46. margin: auto;
  47. -webkit-box-sizing: border-box;
  48. -moz-box-sizing: border-box;
  49. box-sizing: border-box;
  50. vertical-align: baseline; }
  51.  
  52. .progressiveMedia-image {
  53. display: block;
  54. position: absolute;
  55. top: 0;
  56. left: 0;
  57. width: 100%;
  58. height: 100%;
  59. margin: auto;
  60. z-index: 100;
  61. -webkit-box-sizing: border-box;
  62. -moz-box-sizing: border-box;
  63. box-sizing: border-box; }
  64.  
  65. .progressiveMedia .progressiveMedia-canvas {
  66. visibility: hidden;
  67. opacity: 0;
  68. -webkit-backface-visibility: hidden;
  69. backface-visibility: hidden; }
  70. .progressiveMedia.is-canvasLoaded .progressiveMedia-canvas {
  71. visibility: visible;
  72. opacity: 1;
  73. -webkit-transition: visibility 0s linear 0s,opacity .4s 0s;
  74. transition: visibility 0s linear 0s,opacity .4s 0s; }
  75. .progressiveMedia .progressiveMedia-image {
  76. visibility: hidden;
  77. opacity: 0;
  78. -webkit-backface-visibility: hidden;
  79. backface-visibility: hidden; }
  80. .progressiveMedia.is-imageLoaded .progressiveMedia-image {
  81. visibility: visible;
  82. opacity: 1;
  83. -webkit-transition: visibility 0s linear 0s, opacity 1s 0s;
  84. transition: visibility 0s linear 0s, opacity 1s 0s; }
  85.  
  86. .github-star,
  87. .graf-figure {
  88. margin-top: 20px;
  89. margin-bottom: 20px;
  90. }

3. Finally, add the following JavaScript code to your project, create a JavaScript file (e.g., script.js), and paste the code into it. This code will handle the progressive loading of images. It calculates aspect ratios, sets maximum dimensions, and loads images progressively. No further configuration is needed.

  1. /**
  2. * Pilpil v1.0.0 - Progressive Image Loading
  3. * @link https://zafree.github.io/pilpil
  4. * @copyright 2015-2023 Zafree
  5. * @license MIT
  6. */
  7. ;(function() {
  8. 'use strict';
  9.  
  10. // set progressive image loading
  11. var progressiveMedias = document.querySelectorAll('.progressiveMedia');
  12. for (var i = 0; i < progressiveMedias.length; i++) {
  13. loadImage(progressiveMedias[i]);
  14. }
  15.  
  16. // global function
  17. function loadImage(progressiveMedia) {
  18.  
  19. // calculate aspect ratio
  20. // for the aspectRatioPlaceholder-fill
  21. // that helps to set a fixed fill for loading images
  22. var width = progressiveMedia.dataset.width,
  23. height = progressiveMedia.dataset.height,
  24. fill = height / width * 100,
  25. placeholderFill = progressiveMedia.previousElementSibling;
  26.  
  27. placeholderFill.setAttribute('style', 'padding-bottom:'+fill+'%;');
  28.  
  29.  
  30. // set max-height and max-width to aspectRatioPlaceholder
  31. // that is fun
  32. var aspectRatioPlaceholder = progressiveMedia.parentElement,
  33. maxWidth = aspectRatioPlaceholder.offsetWidth,
  34. maxHeight = aspectRatioPlaceholder.offsetHeight;
  35.  
  36. aspectRatioPlaceholder.setAttribute('style', 'max-width:'+maxWidth+'px; max-height:'+maxHeight+'px;');
  37.  
  38.  
  39. // get thumbnail height wight
  40. // make canvas fun part
  41. var thumbnail = progressiveMedia.querySelector('.progressiveMedia-thumbnail'),
  42. smImageWidth = thumbnail.width,
  43. smImageheight = thumbnail.height,
  44.  
  45. canvas = progressiveMedia.querySelector('.progressiveMedia-canvas'),
  46. context = canvas.getContext('2d');
  47.  
  48. canvas.height = smImageheight;
  49. canvas.width = smImageWidth;
  50.  
  51. var img = new Image();
  52. img.src = thumbnail.src;
  53.  
  54. img.onload = function () {
  55. // context.drawImage(img, 0, 0);
  56. // draw canvas
  57. var canvasImage = new CanvasImage(canvas, img);
  58. canvasImage.blur(2);
  59.  
  60. // load canvas visible
  61. progressiveMedia.classList.add('is-canvasLoaded');
  62. };
  63.  
  64.  
  65. // grab data-src from original image
  66. // from progressiveMedia-image
  67. var lgImage = progressiveMedia.querySelector('.progressiveMedia-image');
  68. lgImage.src = lgImage.dataset.src;
  69.  
  70. // onload image visible
  71. lgImage.onload = function() {
  72. progressiveMedia.classList.add('is-imageLoaded');
  73. }
  74. }
  75.  
  76. })();
  77.  
  78. // canvas blur function
  79. CanvasImage = function (e, t) {
  80. this.image = t;
  81. this.element = e;
  82. e.width = t.width;
  83. e.height = t.height;
  84. this.context = e.getContext('2d');
  85. this.context.drawImage(t, 0, 0);
  86. };
  87.  
  88. CanvasImage.prototype = {
  89. blur:function(e) {
  90. this.context.globalAlpha = 0.5;
  91. for(var t = -e; t <= e; t += 2) {
  92. for(var n = -e; n <= e; n += 2) {
  93. this.context.drawImage(this.element, n, t);
  94. var blob = n >= 0 && t >= 0 && this.context.drawImage(this.element, -(n -1), -(t-1));
  95. }
  96. }
  97. }
  98. };

That’s all! hopefully, you have successfully integrated this JavaScript code for progressive image loading. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X