Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
           CodeHim.com

Free Web Design Code & Scripts

       
  • Home
  • Code Snippets
    • Accordion
    • Creative
    • Carousel
    • Date & Time
    • Gallery
    • LightBox
    • Menu & Nav
    • Modal
    • Others
    • Portfolio
    • Social Media
    • Text & Input
    • Video Player
    • Zoom
  • HTML & CSS
  • Bootstrap
  • JavaScript
  • Collections
  • About
  • Contact
  • Buy Me a Coffee

Home / Vanilla JavaScript / Progressive Image Loading in JavaScript

Progressive Image Loading in JavaScript

January 22, 2024January 20, 2024 by Asif Mughal
Progressive Image Loading in JavaScript
Share This:
Code Snippet:Pilpil - Progressive Image Loading
Author: MM Aurangajeb
Published: January 20, 2024
Last Updated: January 22, 2024
Downloads: 1,005
License: MIT
Edit Code online: View on CodePen
Read More
 Demo
Download (File path is not allowed!)

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:

<div class="container">
<figure class="graf-figure">
 <div class="aspectRatioPlaceholder">
 <div class="aspectRatioPlaceholder-fill"></div>
 <div class="progressiveMedia" data-width="YOUR_IMAGE_WIDTH" data-height="YOUR_IMAGE_HEIGHT">
 <img class="progressiveMedia-thumbnail" src="LOW_QUALITY_IMAGE_URL" />
 <canvas class="progressiveMedia-canvas"></canvas> 
<img class="progressiveMedia-image" data-src="HIGH_QUALITY_IMAGE_URL" /> </div>
 </div> 
</figure>
</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.

/**
 * Pilpil v1.0.0 - Progressive Image Loading
 * @link https://zafree.github.io/pilpil
 * @copyright 2015-2023 Zafree
 * @license MIT
 */
figure {
  display: block;
  margin: 0; }

.graf-figure {
  position: relative;
  clear: both;
  outline: 0;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box; }

.aspectRatioPlaceholder {
  position: relative;
  width: 100%;
  margin: 0 auto;
  display: block; }

.aspectRatioPlaceholder-fill {
  display: block; }

.progressiveMedia {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.05); }

.progressiveMedia-thumbnail {
  display: none; }

.progressiveMedia-canvas {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin: auto;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  vertical-align: baseline; }

.progressiveMedia-image {
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  margin: auto;
  z-index: 100;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box; }

.progressiveMedia .progressiveMedia-canvas {
  visibility: hidden;
  opacity: 0;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden; }
.progressiveMedia.is-canvasLoaded .progressiveMedia-canvas {
  visibility: visible;
  opacity: 1;
  -webkit-transition: visibility 0s linear 0s,opacity .4s 0s;
  transition: visibility 0s linear 0s,opacity .4s 0s; }
.progressiveMedia .progressiveMedia-image {
  visibility: hidden;
  opacity: 0;
  -webkit-backface-visibility: hidden;
  backface-visibility: hidden; }
.progressiveMedia.is-imageLoaded .progressiveMedia-image {
  visibility: visible;
  opacity: 1;
  -webkit-transition: visibility 0s linear 0s, opacity 1s 0s;
  transition: visibility 0s linear 0s, opacity 1s 0s; }

.github-star,
.graf-figure {
  margin-top: 20px;
  margin-bottom: 20px;
}

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.

/**
 * Pilpil v1.0.0 - Progressive Image Loading
 * @link https://zafree.github.io/pilpil
 * @copyright 2015-2023 Zafree
 * @license MIT
 */
;(function() {
    'use strict';

    // set progressive image loading
    var progressiveMedias = document.querySelectorAll('.progressiveMedia');
    for (var i = 0; i < progressiveMedias.length; i++) {
        loadImage(progressiveMedias[i]);
    }

    // global function
    function loadImage(progressiveMedia) {

        // calculate aspect ratio
        // for the aspectRatioPlaceholder-fill
        // that helps to set a fixed fill for loading images
        var width = progressiveMedia.dataset.width,
        height = progressiveMedia.dataset.height,
        fill = height / width * 100,
        placeholderFill = progressiveMedia.previousElementSibling;

        placeholderFill.setAttribute('style', 'padding-bottom:'+fill+'%;');


        // set max-height and max-width to aspectRatioPlaceholder
        // that is fun
        var aspectRatioPlaceholder = progressiveMedia.parentElement,
        maxWidth = aspectRatioPlaceholder.offsetWidth,
        maxHeight = aspectRatioPlaceholder.offsetHeight;

        aspectRatioPlaceholder.setAttribute('style', 'max-width:'+maxWidth+'px; max-height:'+maxHeight+'px;');


        // get thumbnail height wight
        // make canvas fun part
        var thumbnail = progressiveMedia.querySelector('.progressiveMedia-thumbnail'),
        smImageWidth = thumbnail.width,
        smImageheight = thumbnail.height,

        canvas = progressiveMedia.querySelector('.progressiveMedia-canvas'),
        context = canvas.getContext('2d');

        canvas.height = smImageheight;
        canvas.width = smImageWidth;

        var img = new Image();
        img.src = thumbnail.src;

        img.onload = function () {
            // context.drawImage(img, 0, 0);
            // draw canvas
            var canvasImage = new CanvasImage(canvas, img);
            canvasImage.blur(2);

            // load canvas visible
            progressiveMedia.classList.add('is-canvasLoaded');
        };


        // grab data-src from original image
        // from progressiveMedia-image
        var lgImage = progressiveMedia.querySelector('.progressiveMedia-image');
        lgImage.src = lgImage.dataset.src;

        // onload image visible
        lgImage.onload = function() {
            progressiveMedia.classList.add('is-imageLoaded');
        }
    }

})();

// canvas blur function
CanvasImage = function (e, t) {
    this.image = t;
    this.element = e;
    e.width = t.width;
    e.height = t.height;
    this.context = e.getContext('2d');
    this.context.drawImage(t, 0, 0);
};

CanvasImage.prototype = {
    blur:function(e) {
        this.context.globalAlpha = 0.5;
        for(var t = -e; t <= e; t += 2) {
            for(var n = -e; n <= e; n += 2) {
                this.context.drawImage(this.element, n, t);
                var blob = n >= 0 && t >= 0 && this.context.drawImage(this.element, -(n -1), -(t-1));
            }
        }
    }
};

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.

Similar Code Snippets:

  • Convert jpg Image to png Using JavaScript

    Convert JPG Image to PNG Using JavaScript

  • JavaScript Image Editor Add Text

    JavaScript Image Editor Add Text

  • JavaScript Draggable Sorting Tags

    JavaScript Draggable Sorting Tags

  • Collapsible Timeline Using CSS3 and Vanilla JS

    Collapsible Timeline Using CSS3 and Vanilla JS

  • Short Story Generator with Specific Words in JavaScript

    Short Story Generator with Specific Words in JavaScript

  • JavaScript Dark Mode Toggle with Local Storage

    JavaScript Dark Mode Toggle with Local Storage

  • JavaScript Timer Countdown Minutes Seconds

    JavaScript Timer Countdown Minutes Seconds

  • JavaScript Progress Bar with Percentage

    JavaScript Progress Bar with Percentage

  • JavaScript Check if Image is Portrait or Landscape

    JavaScript Check if Image is Portrait or Landscape

Asif Mughal

I code and create web elements for amazing people around the world. I like work with new people. New people new Experiences.
I truly enjoy what I’m doing, which makes me more passionate about web development and coding. I am always ready to do challenging tasks whether it is about creating a custom CMS from scratch or customizing an existing system.

Categories Vanilla JavaScript
JavaScript Accordion with Plus Minus
CSS Image Filter Editor in JavaScript

Leave a Comment Cancel reply

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

  • Categories

    • Accordion 22
    • Bootstrap 81
      • Bootstrap Accordion 1
      • Bootstrap Buttons 4
      • Bootstrap Cards 2
      • Bootstrap Carousel 2
      • Bootstrap Dropdowns 2
      • Bootstrap Forms 6
      • Bootstrap Jumbotron 1
      • Bootstrap Modals 2
      • Bootstrap Navbars 6
      • Bootstrap Panels 1
      • Bootstrap Progress Bars 1
      • Bootstrap Text & Input 3
    • Carousel 58
    • Chart & Graph 15
    • Date & Time 49
    • Gallery 39
    • HTML5 & CSS3 201
    • Layout 17
    • LightBox 19
    • Menu & Nav 95
    • Modal 18
    • Others 58
    • Portfolio 8
    • Social Media 10
    • Text & Input 120
    • Vanilla JavaScript 163
    • Zoom 12

You May Like

Alert (7) Analog Clock (4) Analog Clocks (5) Back to Top (4) Calculator (16) Calendar (5) Chart (3) Color Picker (4) Contact Us Forms (5) Countdown Timer (6) Datepicker (9) Digital Clocks (10) Drag and Drop (4) Dropdown Menu (23) File Uploader (4) Hamburger Menu (9) Horizontal Menu (24) Hover Effects (5) HTML5 Canvas (8) Image Sliders (40) Mega Menu (11) Modal (5) Multi-Level Menu (9) News Ticker (4) Notification (9) Off-Canvas Menu (10) Pagination (5) Parallax (8) Popup Lightbox (20) Progress Bar (5) Range Sliders (4) Scrolling Effects (28) Search Box (4) Select Dropdown (4) Shopping Cart (3) Side Menu (16) Slideshow (19) Social Share Buttons (3) Tabs (9) Text (11) Timeline (5) Timer (4) Tooltip (4) Typing Effect (6) Vertical Menu (14)

Latest Code Snippets

  • Common Open Source Security Vulnerabilities and How to Mitigate ThemCommon Open Source Security Vulnerabilities and How to Mitigate Them
    October 12, 2024
  • Animating Grid-column on Hover Using CSSAnimating Grid-column on Hover Using CSS
    April 1, 2024
  • Star Trails Animation On Mousemove in JavaScriptStar Trails Animation On Mousemove in JavaScript
    March 31, 2024
  • Gravity Button Using Pure CSSGravity Button Using Pure CSS
    March 31, 2024
  • Padlock Toggle Switch in CSSPadlock Toggle Switch in CSS
    March 31, 2024
  • Scroll-driven Animations in Pure CSSScroll-driven Animations in Pure CSS
    March 31, 2024
  • Interactive Notification Center UI in Vanilla JSInteractive Notification Center UI in Vanilla JS
    March 31, 2024
  • Emoji Spinner in Vanilla JavaScriptEmoji Spinner in Vanilla JavaScript
    March 31, 2024
  • Reveal Secret Code Using CSSReveal Secret Code Using CSS
    March 31, 2024
  • Toggle Button in CSS With Stretchable Elastic EffectToggle Button in CSS With Stretchable Elastic Effect
    March 31, 2024

Popular

  • 65+ Login Page in HTML with CSS Code Sample Simple to Difficult - 947,396 views
  • 25+ Best JavaScript Shopping Cart Examples with Demo - 211,933 views
  • Bootstrap Multiselect Dropdown with Checkboxes - 150,948 views
  • Bootstrap 5 Buttons with Icon and Text Tutorial & Demo - 112,357 views
  • 19+ Bootstrap Select Dropdown with Search Box Tutorial & Examples - 101,034 views
  • Bootstrap 5 Sidebar Menu with Submenu Collapse/Hover Tutorial Demo - 88,103 views
  • 99+ Social Media Buttons HTML Code Sample & Tutorial - 86,392 views
  • 19+ Bootstrap 5 Mega Menu Responsive/Drop Down Examples - 86,388 views
  • Bootstrap 4 Modal Popup Login Form Tutorial & Demo - 82,145 views
  • Bootstrap Vertical Menu with Submenu on Click - 80,199 views

Advertisement

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...

CodeHim
  • About
  • Contact Us
  • Terms and Conditions
  • Privacy Policy
Top Categories
  • Bootstrap Snippets
  • JavaScript Snippets
  • HTML CSS Snippets
  • Menu & Nav Snippets
Get in Touch

Follow us on social media to be updated with latest web design code & scripts...

All Rights Reserved © 2026 - CodeHim Inc

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

F5
X