Skip to main content

Command Palette

Search for a command to run...

Improve UI performance using window.onload event

window.onload event is very useful event when you are dealing with huge files like, images, video etc. on frontend.

Published
1 min read
Improve UI performance using window.onload event
K

I am a web developer - both front end developer / designer and backend programmer and passionate about new technologies.

window.onload

It called, when the entire page load including imges, css, DOM etc.

  window.onload = function(){
         console.log("Application Loaded")
  }

It is common for all of us front end developers that, sometime images are huge in size and taking time to load on the application in that case our UI shows distorted. see the screen shot.

Window-Onload-KMT.png In the above example, i used window.onload. that's why its showing loading message below the image because the images are not fully loaded.

So this winodw.onload event can solve that issue. using this event we can show a loading message or block the screen or show placeholder images till the image or file not completely loaded.

Window-Onload-KMT1.png In the above image, you can see the message, "Application Loaded", it means all the resources are completely loaded now.

The complete code is here:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script>
            function onloaded(){
                var status = document.getElementById('status');
                var loader = document.getElementById('loader')
                status.innerText = "Application Loaded";
                loader.style.display='none'
            }
            window.onload = onloaded;
        </script>
        <title>Window Onload | KMT</title>
    </head>
    <body>
       <div style="text-align: center;">
            <img src="https://images.pexels.com/photos/7974362/pexels-photo-7974362.jpeg" width="300px" height="400px"/>
            <img src="https://images.pexels.com/photos/2377915/pexels-photo-2377915.jpeg" width="300px" height="400px"/>
            <img src="https://images.pexels.com/photos/3626589/pexels-photo-3626589.jpeg" width="300px" height="400px"/>
            <h1 class="display-6" id="status">Loading in progress...</h1>
        </div>
    </body>
</html>

Download code from Git repo.

Demo