Loading Website Content, Track your Progress

I'm facing an issue with the website loading progress bar. The script I'm using for the progress bar is not functioning correctly on the Web server www.example.com. Even though the website is live on the web server, the problem is that the progress bar only starts after a delay once the site is opened.

Is there a way to make the progress bar start as soon as the website is opened?

Thank you.

$(window).load(function(){
    var width = 100,
    perfData = window.performance.timing,
    EstimatedTime = -(perfData.loadEventEnd - perfData.navigationStart),
    time = parseInt((EstimatedTime/1000)%60)*100;

    // Loadbar Animation
    $(".loadbar").animate({
      width: width + "%"
    }, time);

    // Loadbar Glow Animation
    $(".glow").animate({
      width: width + "%"
    }, time);

    // Percentage Increment Animation
    var PercentageID = $("#precent"),
        start = 0,
        end = 100,
        durataion = time;
        animateValue(PercentageID, start, end, durataion);

    function animateValue(id, start, end, duration) {

      var range = end - start,
          current = start,
          increment = end > start? 1 : -1,
          stepTime = Math.abs(Math.floor(duration / range)),
          obj = $(id);

      var timer = setInterval(function() {
        current += increment;
        $(obj).text(current + "%");
        
        if (current == end) {
          clearInterval(timer);
        }
      }, stepTime);
    }

    // Fading Out Loadbar on Finised
    setTimeout(function(){
      $('.preloader-wrap').fadeOut(300);
    }, time);

});

Answer №1

If you're looking to enhance your code, consider utilizing $(document).ready(function(){ instead of $(window).load(function(){. This will ensure a more efficient loading process.

The ready event triggers after the HTML document is loaded, whereas the onload event occurs once all content, like images, are also loaded.

The main advantage of using the ready event is that it executes at an earlier stage post-document load, allowing code to enhance page elements without waiting for complete content loading.

Credits to Guffa for providing insights in response to this query

This approach ensures that the wait time is minimized by focusing solely on the HTML document's loading speed. Modify your script as shown below:

$(document).ready(function(){
   // add your additional code here    
});

Update: Consider incorporating this snippet into your code:

$(document).ready(function(){
  var width = 100,
      perfData = window.performance.timing,
      EstimatedTime = -(perfData.loadEventEnd - perfData.navigationStart),
      time = parseInt((EstimatedTime/1000)%60)*100;

  $(".loadbar").animate({
    width: width + "%"
  }, time);

  $(".glow").animate({
    width: width + "%"
  }, time);

  var PercentageID = $("#precent"),
      start = 0,
      end = 100,
      duration = time;
      animateValue(PercentageID, start, end, duration);

  function animateValue(id, start, end, duration) {

    var range = end - start,
        current = start,
        increment = end > start? 1 : -1,
        stepTime = Math.abs(Math.floor(duration / range)),
        obj = $(id);

    var timer = setInterval(function() {
      current += increment;
      $(obj).text(current + "%");
      if (current == end) {
        clearInterval(timer);
      }
    }, stepTime);
  }

  $(window).load(function(){
    $('.preloader-wrap').fadeOut(300);
    $('.wrap').fadeIn(300);
  });
});

Make sure all your content is enclosed within the .wrap div for this implementation to work seamlessly.

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

Looking for a JavaScript code to create a text link that says "submit"?

Here is the code I have, where I want to utilize a hyperlink to submit my form: <form name="form_signup" id="form_signup" method="post" action="/" enctype="multipart/form-data"> ... <input type="submit" value="Go to Step 2" name="completed" /> ...

Holding off on executing the event handler until the completion of another function

On our website, we've integrated a 3rd party solution that cannot be directly updated. However, I can insert my own JavaScript code to manipulate the solution. This third-party tool includes a button that triggers an AJAX request. Before this request ...

Is it possible to retrieve JavaScript object properties using HTML elements?

I have fetched an array of objects using jQuery.getJSON(). Each object should be represented by an HTML div element, allowing users to click on the element and access all properties of the corresponding object. What is the most efficient approach for achie ...

Formulate a targeted search request according to the selected radio button option

I'm working on a form that looks like this: <form> <input type="text" id="searchedWord" class="form-control form-control-lg" value="words here"/> <button type="submit" id="f ...

What is the reason that Object.keys(window) or for(k in window) does not include the Math object?

As I work on creating a JavaScript editor autocomplete feature, my goal is to showcase all available top-level elements. So far, I've experimented with: Object.keys(window) as well as for (k in window) However, it seems like neither method include ...

Is it possible to modify the background color of a select option menu when hovering over it?

It turns out that the default background color of the select option menu changes to blue when it is hovered over. However, I would like to personalize and adjust it to my preference using Bootstrap 5 and CSS. Any assistance with this customization would ...

Display an icon within an HTML element when the content inside it exceeds its boundaries

Looking to display a copy to clipboard icon when the content inside a div overflows I am using ngFor to iterate through four divs, and if any of those divs is overflowing, I want to show an icon specific to that respective div. <div *ngFor div of Four ...

Is there a streamlined approach to reducing the code for an Angular Bootstrap card with a fixed length and height?

Is there a more efficient way to distribute a fixed number of cards with fixed dimensions in three rows? Currently, I am manually coding all 33 cards spread across 3 rows - 11 cards per row. Please excuse any mistakes in my code as I am still a beginner a ...

JavaScript menu that pops up

Hello everyone, I've recently created an HTML5 file that, when clicked on a specific href link, is supposed to display an image in a smooth and elegant manner. However, so far it hasn't been working for me as expected. Instead of smoothly popping ...

How can I wrap text in Angular for better readability?

I've created a calendar in my code that displays events for each day. However, some event descriptions are too long and get cut off on the display. Even after attempting to use Word Wrap, I still can't see the full text of these events unless I c ...

Exploring Vue's reactivity using the composition API and cloning props

In my current component setup, I am receiving props from a parent. However, I am facing an issue where I only want to clone these props without any changes affecting the parent component. <template> <input-text v-model="form.name" /&g ...

Calling a Coldfusion function from JavaScript/jQuery using a remote server connection

Although I am well-versed in JavaScript/jQuery, I am a newcomer to ColdFusion. After extensive research, I still can't figure out what seems like it should be a simple problem. My goal is to trigger a server-side call to a ColdFusion function from wi ...

Which is better for a jQuery/Ajax Login Box: JSONP or CORS?

To create a login box that meets the specified criteria, the following must be taken into consideration: Develop it as a versatile UI Component that can be utilized in various sections of a website Allow for multiple instances of this component to coexis ...

Utilize Ajax to transfer an image from an input form to a PHP script

I am currently working on a basic HTML page that includes an image upload form. Here is the code for the form: <input type='file' id='image_uploaded' accept='image'/> <input type='submit' id="upload_image"/ ...

The Year as a Reference Point

I came across an interesting issue while working with dictionaries and JSON in sessionStorage. Initially, I had a dictionary structured like this: "name" : { "2016" : { "1" : "info" } } After successfully adding it to sessionS ...

Issue encountered while executing tasks in the Gruntfile.js file

Having trouble with Grunt concatenating my CSS files into one named production.css Below is the output I received from the command prompt: C:\Users\josha\Desktop\Repos\AJAX Project - Grunt Test>grunt C:\Users\josha& ...

The Ocelot API Gateway is a powerful tool for managing

I encountered an issue while working on my API gateway project. I initially installed the latest version of Ocelot (16.0.1), but it did not function correctly. The problem was resolved by reverting back to Ocelot version 15.0.6, while keeping my .NET Core ...

Adding an item to the collection

When I log my cartProducts within the forEach() loop, it successfully stores all the products. However, if I log my cartProducts outside of the loop, it displays an empty array. var cartProducts = []; const cart = await CartModel .fin ...

Establishing a secondary Node.js service for local communication with Parse Server

My current project involves using Node.js + Parse Server for an application. I have been utilizing the Parse SDK from the client side, but there are still many changes and refactors that need to be made. One issue I am facing is that certain logic should b ...

Create an array populated with unclosed HTML tags that need to be rendered

I'm trying to display a simple list, but it seems like React is having trouble rendering unclosed HTML elements that are pushed onto the list. This results in an error: ReferenceError: el is not defined If I use single quotes (') bookingStat ...