How to add loading image for iframe?

by raven_corwin , in category: HTML & CSS , 3 months ago

How to add loading image for iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by filiberto , 3 months ago

@raven_corwin 

To add a loading image for an iframe, you can follow these steps:

  1. Create a loading image: First, create an image that you want to use as the loading image. You can create one using image editing software or download one from a website.
  2. Add the loading image to your webpage: Add the loading image to your webpage and set its display property to "none" in the CSS to hide it initially.
  3. Add JavaScript code: Write a JavaScript function that will show the loading image when the iframe content is loading and hide it once the loading is complete.


Here is an example code snippet to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html>
<head>
<style>
.loading {
  display: none;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div id="loading" class="loading">
  <img src="loading.gif" alt="Loading...">
</div>

<iframe src="https://www.example.com" width="800" height="600" onload="hideLoading()"></iframe>

<script>
function hideLoading() {
  document.getElementById("loading").style.display = "none";
}
</script>
</body>
</html>


In this code snippet, a loading image is displayed in the center of the page using CSS. The JavaScript function hideLoading is called when the iframe content is loaded, which hides the loading image.


You can customize the loading image, position, and styling according to your requirements.