TheRogerLAB Codes

Display preloader while image is loading

  Dec, 2021

Introduction

When we display an image on our website it will take some time to load. The user will see only the text and then the image loading piece by piece. One way that this is not annoying for the user is by using loading cards. Here are two options:

Option 1: Background color while loading a background image

HTML Code:

<div class='myElement'></div>

CSS Code:

.myElement{
  width:300px;
  height:300px;
  background-repeat: no-repeat;
  background-size: cover; 
  background-color: #e8e8e8;
}

JS Code:

//Create an image
var bgImg = new Image();

//Define its onload event
bgImg.onload = function(){
  
  //Select the element to change the background using the image
   var el = document.querySelector(".myElement");
   el.style.backgroundImage = 'url(' + bgImg.src + ')';
  
};
bgImg.src = "https://www.mysite.com/images/myImage.jpg";

Option 2: Animated loading card while loading image source

HTML Code

<div class="preload-card" id="container">
  <div>
    <img style="width:100%;" id="myElement1">
  </div>     
</div>

CSS Code

#container{
  width:200px;
  height:200px
}
.preload-card {
  animation-duration: 1.25s;
  animation-fill-mode: forwards;
  animation-iteration-count: infinite;
  animation-name: preload-card-animation;
  animation-timing-function: linear;
  background: #f9f9f9 ;
  background: linear-gradient(to right, #f9f9f9 8%, #f0f0f0 18%, #f9f9f9  33%);
  background-size: 800px 104px;  
  position: relative;
}
@keyframes preload-card-animation {
  0% {
    background-position: -468px 0;
  
}
  100% {
    background-position: 468px 0;
  
}
}

JS Code

//Create an image
var bgImg1 = new Image();

//Define its onload event
bgImg1.onload = function(){
  
  //Select the element to change the image source
   var el = document.querySelector("#myElement1");
   el.src = bgImg1.src;
  
  //Once loaded remove loading cards css class
   document.querySelector("#container").classList.remove('preload-card');
};
bgImg1.src = "https://www.mysite.com/images/myImage.jpg";

Check a working demo for this code:

SEE DEMO RATE THIS ARTICLE
TheRogerLAB Codes
Powered by TheRogerLAB Sandbox

info@therogerlab.com