Is there a method to track the progress of webpage loading?

I am working on a website built with static HTML pages. My goal is to implement a full-screen loading status complete with a progress bar that indicates the page's load progress, including all images and external assets. Once the page has fully loaded, the loading screen will disappear, revealing the content to the user.

Although I have successfully detected when the page has completed loading by using the 'load' event listener on the window object, I am facing challenges in getting the progress bar to display as expected. I aim to show the progress in percentage format, which requires me to calculate the overall size of the page including all assets and monitor the resources being transferred so I can convert it into a percentage value.

After conducting some research, I have found that there isn't a simple solution for this task. However, I have noticed many websites implementing similar progress bar loading animations.

My question now is: How can I achieve a similar effect on my website? I want to provide users with a visual representation of the loading progress in percentage as they wait for the page to load.

Answer №1

Here is one potential method to achieve this on a static page without resorting to deception

Adjustments can be made as needed. For instance, if I reach 81%, I use a timeout to display the content regardless.

<!DOCTYPE html>
<html lang="en>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Page Loading Progress</title>
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" onload="updateProgress()">
  <!-- Additional CSS links here -->
  <style>
   
    .image-column {
      column-count: 2;
    }
    
    img {
      width: 100%;
      margin-bottom: 10px;
    }
  </style>
  <script>
    let loadCounter = 0;
    let totalElements = 16;
    const updateProgress = () => {
      loadCounter++;
      const progress = (loadCounter / totalElements) * 100;
      const progressBar = document.getElementById('progressBar');
      progressBar.style.width = progress + '%';
      progressBar.textContent = Math.round(progress) + '%';

      if (progress === 100) {
        document.querySelector('.progress').hidden = true;
        document.querySelector('main').hidden = false;
      }
    }
    setTimeout(() => {
      document.querySelector('.progress').hidden = true;
      document.querySelector('main').hidden = false;
    },3000)
    
  </script>
</head>

<body>
  <header>
    <div class="progress">
      <div class="progress-bar" role="progressbar" style="width: 0%;" id="progressBar">0%</div>
    </div>
  </header>

  <main hidden>
    <div class="image-column">
      <!-- 10 Images from Lorem Pixel -->
      <img src="http://placekitten.com/200/300" onload="updateProgress()">
      <img src="https://placekitten.com/200/300" onload="updateProgress()">
      <img src="https://placekitten.com/200/300" onload="updateProgress()">
      <img src="https://placekitten.com/200/300" onload="updateProgress()">
      <img src="https://placekitten.com/200/300" onload="updateProgress()">
      <img src="https://placekitten.com/200/300" onload="updateProgress()">
      <img src="https://placekitten.com/200/300" onload="updateProgress()">
      <img src="https://placekitten.com/200/300" onload="updateProgress()">
      <img src="https://placekitten.com/200/300" onload="updateProgress()">
      <img src="https://placekitten.com/200/300" onload="updateProgress()">
    </div>
  </main>

  <!-- jQuery and Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.7.1.slim.min.js" onload="updateProgress()"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" onload="updateProgress()"></script>

  <script>
    // totalElements = document.querySelectorAll('script, link, img').length;
    
  </script>
</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble updating the value in the toolbar?

Here is an example that I added below: When I click the add button, the value of the "newarray" variable is updated but not reflected. I am unsure how to resolve this issue. This function is used to add new objects: export class AppComponent { ne ...

Mongoose Does Not Allow for Duplicate Data Submissions

I'm currently working on a project to develop a basic blog application. Everything works smoothly when submitting content to the database for the first time, but if you try to submit again, Node crashes unexpectedly. I've been struggling to pinpo ...

Shortening a jQuery If-Else Statement in JavaScript

I am working on a snippet of code and need some help. Here is the code: <script type="text/javascript"> $(window).load(function() { if(!$.browser.msie){ $('#myDiv').animate({opacity: 1}, 300); } else if ($.browser.msie) { ...

Create a custom element in React to detect and encapsulate links

I could really use some assistance with this issue. I have a bunch of text blocks containing links and have been utilizing linkifyjs's React component to automatically wrap the links in anchor tags. However, now I am looking to add a custom button nex ...

Experiencing difficulties in displaying a React element that is being passed as a prop

One of my components looks like this: const Chip = (props) => { const ChipIcon = props.icon; let deleteButton = null; if (!props.readOnly) { deleteButton = <Delete style={styles.deleteButton} onTouchTap={props.onRemove} /& ...

Enhance your HTML code using JavaScript (specifically jQuery)

Is there a way for me to transform the following code into a more visually appealing format? <td> <a href="/Test/Page/2">Previous</a> <a href="/Test/Page/1">1</a> <a href="/Test/Page/2">2</a> 3 ...

What's the best way to switch between colors in a Vue list?

I have a custom tree-view component that I'm working on: <template> <li class="main__li list" :style="{'margin-left': `${depth * 20}px` ,'background-color': `${col}`}" @click="toggle(e); getEl( ...

Using Angular's ng-repeat to iterate through an array and display its objects within another array

One of my tasks involves retrieving json objects through a simple post method. The json contains multiple campaigns, organized in an array structure. Each campaign holds slots, which are also arrays with one or more base_image elements. My goal is to di ...

Ways to retrieve output from a JavaScript function

How can I successfully return the result from response.on within the signIn function? const signIn = async (password) => { var request = new DeviceAuthQuery(); request.setPassword(password); var response = client.authenticate(request, {}, (err, ...

Storage in Ionic and variable management

Hello, I'm struggling to assign the returned value from a promise to an external variable. Despite several attempts, I have not been successful. export class TestPage { test:any; constructor(private storage: Storage) { storage.get('t ...

What steps are involved in creating a video playlist with YouTube videos?

Is there a way to create a dynamic video playlist that supports embedded YouTube videos without refreshing the page? If a user clicks on another video, I want the video to change dynamically. You can check out this for an example. Do jPlayer, Video.js, Fl ...

Exploring the controller logic in Sails.js index.ejs

I'm struggling to understand how to integrate dynamic logic into the homepage of my Sails.js application. Currently, the homepage is static, but I want to display data on the index.ejs page. I have a MainController with an index function that retrieve ...

Ways to insert HTML text into an external webpage's div element without using an iframe

Is it possible to generate HTML and SVG code based on the position of a Subscriber on a web page or within a specific div? I would like to provide some JavaScript code that can be inserted inside a particular div on the page. Using an iframe is not ideal ...

Is there a CSS3 Selector With Similar Functionality to jQuery's .click()?

For a few years now, I have been utilizing a pure CSS navigation system. However, with the recent increase in mobile site projects at my workplace, I am encountering issues with drop-down menus not functioning properly on mobile devices. Despite this chall ...

Steps to incorporate the latest Material Design Bottom App Bar into your project

In our company, we are currently utilizing Vue and SCSS for constructing our latest Progressive Web Application. Depending on specific conditions relating to the user's profile, we need to switch out the left drawer with a Bottom App Bar. Although we ...

A warning is triggered when attempting to return a non-returning function from a Promise

I have a nodejs express app where I am utilizing a library that operates on a typical callback interface for executing functions. However, my persistence layer is set up using a promise-based approach. The following code snippet is causing me some concern: ...

The value of a string in jQuery turns undefined once it is used as an argument

Hello there, Currently, I am working on a personal project involving NodeJS and Electron. The project is a basic text editor as of now. However, I am facing an issue when attempting to pass the value of a text-area to a function before saving it to a file ...

`"Unable to execute the 'ng build --env=prod' command"`

I have a JavaScript website that I need to rebuild with some changes I made. In order to build the application, I was instructed to run this command from the source files directory: ng build –env=prod However, when I try to do so, I keep encountering t ...

Issues with JavaScript Content Loading in epub.js on a Website

Hey there, I'm currently experimenting with the epub.js library and trying to set up the basics. However, I'm encountering an issue where the ebook is not showing up in my browser: <!DOCTYPE html> <html lang="en"> <head&g ...

Angular JS allows you to easily remove the # symbol from a URL, improving the

I am encountering a problem with the "#" symbol in my angular js website's URL. I need to remove the # from the URL but the method provided isn't working and the site is not displaying properly. Can someone advise me on how to successfully remove ...