The idea here is that there is an image placement container with a gray background. Only when the image is loaded will it show. This prevents a ‘stuttered’ appearance as the image actually loads and is more appealing. Once the image is actually loaded, the visibility css style is switched from ‘hidden’ to ‘visible’
<html lang="eng">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
#image-background{
background: gray;
width: 700px;
height: auto;
}
img {
background-color: red;
max-width: 100%;
max-height: 100%;
visibility: hidden;
}
</style>
</head>
<body>
<main>
<div id="image-background">
<img id="image">
</div>
</main>
</html>
<script>
//let logo = document.getElementById("logo");
let logo = document.querySelector("#image");
/* logo.addEventListener('load', (event) => {
console.log('Logo has been loaded!');
logo.style.visibility="visible";
});*/
logo.onload = (event) => {
console.log('Logo has been loaded!');
logo.style.visibility="visible";
};
logo.src = "/webimages/boris-debusscher-9Rtp9uvTs3Q-unsplash.jpg" + "?_=" + (+new Date());
</script>
Note with the code, there are two ways of doing this.
By using the load event listener:
logo.addEventListener('load', (event) => {
console.log('Logo has been loaded!');
logo.style.visibility="visible";
});
Or by using the onload even:
logo.onload = (event) => {
console.log('Logo has been loaded!');
logo.style.visibility="visible";
};
Both work just fine.