How to do image preloading with javascript?


The preload attribute specifies how the author thinks about the media file should be loaded when the page loads. The preload attributes allow the author to provide hints to the browser about how much time should take to load a page, it will lead to the best user experience.

Preload also tells the browser about critical resources that you want to load as soon as possible. This is especially useful for resources that are not easily appreciable, such as fonts included in stylesheets, background images, or resources loaded from a script.

Using preload helps here because the images start loading ahead of time and is likely to already be there when the browser needs to display it.

There are a few types of image preload in JavaScript.

Example 1: Using event listeners in JavaScript

In the following example, we are preloading the images. If the images are fully loaded in the browser, then it will show the images.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Document</title>
</head>
<body>
   <p>onload Event</p>
   <img id="img1" src="https://www.tutorialspoint.com/java/images/java-mini-logo.jpg" style="max-width: 50%;">
   <img id="img2" src="https://www.tutorialspoint.com/javafx/images/javafx-mini-logo.jpg" style="max-width: 50%;" >
   <script>
      const img1 = document.getElementById("img1");
      const img2 = document.getElementById("img2");
      img1.addEventListener("load", function(){
         alert("first image is loaded");
      });
      img2.addEventListener("load", function(){
         alert("second image is loaded");
      })
   </script>
</body>
</html>

Example 2

In the following example, we have created two functions first is preloader() and the second is addLoadEvent() and using the onload event listener.

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Document</title>
</head>
<body>
   <img id="img1" src="https://www.tutorialspoint.com/java/images/java-mini-logo.jpg" style="max-width: 20%" />
   <img id="img2" src="https://www.tutorialspoint.com/javafx/images/javafx-mini-logo.jpg" style="max-width: 20%" />
   <script>
      function preloader() {
         if (document.getElementById) {
            document.getElementById("img1");
            document.getElementById("img2");
         }
      }
      function addLoadEvent(func) {
         var oldonload = window.onload;
         if (typeof window.onload != "function") {
            window.onload = func;
         } else {
            window.onload = function () {
               if (oldonload) {
                  oldonload();
               }
               func();
            };
         }
      }
      addLoadEvent(preloader);
   </script>
</body>
</html>

Updated on: 19-Dec-2022

940 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements