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

Prioritizing nth child over the first child

I have a situation where I need to maintain 3 different styles in a patterned design without altering the classes on the HTML side. I have been attempting to achieve this using nth-child selectors. However, I am facing an issue where my first class is bein ...

Sending a batch of items through an ajax request

I am faced with a challenge where I have a collection of data stored within multiple objects. Within each object, there is an ID and a status, while the main object contains a type and form id. The issue arises when trying to post the result via ajax as ...

Utilizing Jquery for toggling HTML elements and styling with CSS

I'm trying to implement a jQuery toggle button that switches between two states below; When I click the Toggle Button/link, everything in picture A (above the red line) should be hidden. Clicking the toggle button again would make it reappear. I&apo ...

Node.js server experiencing delays handling multiple requests causing timeouts

As someone who is not very experienced with node, I appreciate your patience. I have a node.js server with 2 routes. Throughout the day, both routes receive requests simultaneously. Route 1 runs smoothly, while route 2 is a long-running process that invol ...

Clicking on a checkbox within an HTML table that incorporates handlebar and Express.js

My situation involves a HTML table within a form that is being populated with Handlebars. I need to be able to select certain rows in the table using checkboxes, and upon form submission through a POST request in an Express.js framework, I require the JSON ...

Enhancing User Experience with AJAX Page Loading and Progress Tracker

I'm looking to create a jQuery AJAX page load with a progress bar displayed at the top. I came across a helpful example of what I have in mind here. Any tips on how to get started would be greatly appreciated. This will be implemented on a WordPress ...

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

How to send parameters to the jQuery delete button click event handler

Here is the jQuery code I am working with: $('#btnDelete').click( function() {//Do the delete here via jquery post}); In my table, each row has a delete button like this: <a id="btnDelete">Delete</a> I need to pass parameters to t ...

Having trouble creating a PDF from HTML

Having trouble with generating PDFs using various libraries as I keep encountering the following error: Fatal Error: spawn UNKNOWN The code snippet looks like this: mammoth.convertToHtml({ path: './backend/common/template.docx' } ...

Is it sufficient to only capture 4xx errors?

Is it necessary to catch both 4xx and 5xx errors, or is catching just 4xx errors sufficient? In regular testing of my code, when would a 5xx error even occur? ...

What is a method to position an <img> on top of text without obscuring the text or resorting to CSS background or text-indent

To view the related code snippet, click on this link: http://jsfiddle.net/Ws8ux/ Is there a way to position the text under the logo without hiding it through display:none or text-indent? I am aiming to bring the image up while keeping the logo in the back ...

What is the best way to accurately establish a new name for the evolving scope

var tags_offset=[]; $scope.getRelations = function(id, ref, subRef=0){ tags_offset[ref+'-'+subRef]=0; $http.get( CONS.appHttp+ '/tags.php?ID='+id +'&ref='+ref +'&contentType='+subRe ...

Activate the jquery function when the content of the <ul> element changes

Looking for a way to trigger a jQuery function when the content of an unordered list (ul) changes. Check out the code I've written below: JavaScript jQuery(document).ready(function($) { $('.ProductList').on('change', fun ...

Utilizing Angular 9's inherent Ng directives to validate input components within child elements

In my current setup, I have a text control input component that serves as the input field for my form. This component is reused for various types of input data such as Name, Email, Password, etc. The component has been configured to accept properties like ...

A bug encountered with AngularJS and dojox.charting: Error message 'nodeType' of null

My goal is to dynamically populate a div with various graphs from Dojo, depending on the current data model. However, I keep encountering the error message "Cannot read property 'nodeType' of null" when running my code. I suspect that this issu ...

Are HTML entities ineffective in innerHTML in javascript?

Take this example: <script type="text/javascript> function showText() { var text = document.getElementById("text-input").value; document.getElementById("display").innerHTML = text; } </script> <?php $text = "<html>some ...

Utilize vue-resource for updating information in the database

Within my Vue component, I have the following data setup: data() { return { revenueChart: '', limit: 12, labels: '', datasets: '' } }, In addition, there is a method that utilizes vue- ...

Optimal methods for refreshing website lists

I've designed an ASP.NET MVC application with a list that displays all the current items from a database. There is also a button that triggers a popup-dialog to create a new entry. The goal is to automatically add the new item to the list once it is c ...

Jumbling a word by shuffling its letters into a random order

The objective of the program is to take the word you input into a box, split it into an array of letters, and then shuffle them. Following that, it should capitalize the first letter and lowercase the rest before displaying the result in the same box. I a ...

Show 1 Blog Post on a Separate AngularJS Page

I would like to show only Test Post 1 on the next HTML page titleDetails.html when the user clicks on Test Post 1 in index.html 1) titleDetails() in index.html: <a ng-click="titleDetails(post)">{{ post.title }} </a> 2) Controller Variables a ...