Skip to content

Instantly share code, notes, and snippets.

@aziis98
Last active November 4, 2018 23:34
Show Gist options
  • Select an option

  • Save aziis98/b516aabd586a725b6da928e3498c1bc3 to your computer and use it in GitHub Desktop.

Select an option

Save aziis98/b516aabd586a725b6da928e3498c1bc3 to your computer and use it in GitHub Desktop.

Loading Bar Image

A prototype for an image with a progress bar that show the progress of download of the image.

Usage

First create an HeavyImage instance with the target URL and then place the internal element somewhere on the page using theImage.$element and when ready stard downloading the image with theImage.load().

const images = Array(3).fill(0).map(() => {
  return new HeavyImage("https://upload.wikimedia.org/wikipedia/commons/3/3d/LARGE_elevation.jpg");
});

images.forEach(img => {
  document.body.appendChild(img.$element);
  
  img.$element.style.margin = '1rem';
  img.$element.style.width = '200px';
  img.$element.style.height = '200px';
  
  img.$element.onclick = function() {
    img.load();
  }
});

images.forEach(img => {
  img.load();
});
// ================ //
// Heavy Image Code //
// ================ //
const HeavyImage = function (url) {
const self = this;
// Creates the internal "div.heavy-image" element
this.$element = document.createElement("div");
this.$element.classList.add('heavy-image');
this.load = function () {
// Setups the request
const req = new XMLHttpRequest();
req.open('GET', url, true);
req.responseType = 'arraybuffer';
// When the request is completed this sets the resulting blob
// to the backgroundImage of the internal element and resets
// to 0 the "--percent" variable.
req.onload = function(e) {
self.$element.style.backgroundImage = 'url(' + URL.createObjectURL(new Blob([this.response])) + ')';
self.$element.style.setProperty('--percent', 0);
};
// Updates and internal variable and the "--percent" CSS variable.
req.onprogress = function(e) {
self.completedPercentage = parseInt((e.loaded / e.total) * 100);
self.$element.style.setProperty('--percent', self.completedPercentage);
};
// Setting intial values for things.
req.onloadstart = function() {
self.completedPercentage = 0;
self.$element.style.setProperty('--percent', 0);
};
req.send();
};
}
.heavy-image {
position: relative;
border: 1px solid #ddd;
background-position: center;
background-size: contain;
background-repeat: no-repeat;
}
.heavy-image::before {
content: '';
position: absolute;
background: #ffffff88;
border: 1px solid #444;
opacity: var(--percent);
left: 50%;
top: 50%;
width: calc(100% - 20px);
height: 10px;
transform: translate(-50%, -50%);
}
.heavy-image::after {
content: '';
position: absolute;
background: #444;
top: 50%;
left: calc(11px);
width: calc(var(--percent) * 1% - 20px - 2px);
height: 8px;
transform: translate(0, -50%);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment