Display the LOADING indicator until the entire page has finished loading

Here is the JavaScript code that I am currently using:

function generateRequest(){
    var request;
    if(window.XMLHttpRequest){
        // Works with Firefox, Safari, Opera
        request = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
        // Works with IE 5+
        request = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else{
        // Error message for old browsers
        alert('Your browser does not support this function');
    }
    return request;
}

// Create the XMLHttpRequest Object
var http = generateRequest();

function sendCustomRequest(method, url, targetDiv){
    target = targetDiv;
    if(method == "get" || method == "GET"){
        http.open(method,url);
        http.onreadystatechange = handleServerResponse;
        http.send(null);

    }
}

var target; 

function handleServerResponse(){
    if(http.readyState == 4 && http.status == 200){
        var content = http.responseText;
        if(content){  
            document.getElementById(target).innerHTML = content;
        }
    }      
}

This specific section of the code:

            document.getElementById(target).innerHTML = content;

is responsible for updating the webpage with the response. How can I display a "Loading" message while waiting for the page to fully load?

Answer №1

What do you think about including a Div element containing your loading HTML in the body like this?

<div id="loadingDiv" class="hiddenClass">Fancy rotating image goes here</div>

You can create a CSS class with display:none, then use it as follows:

http.onreadystatechange = handleResponseTwo;
var myDiv = document.getElementById('loadingDiv');
myDiv.className = "showClass";

After that, include:

document.getElementById(head).innerHTML = response;

and add:

var myDiv = document.getElementById('loadingDiv');
myDiv.className = "hiddenClass";

Put it all together:

function createRequestObject(){
    var req;
    if(window.XMLHttpRequest){
        //For Firefox, Safari, Opera
        req = new XMLHttpRequest();
    }
    else if(window.ActiveXObject){
        //For IE 5+
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else{
        //Error for an old browser
        alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
    }
    //alert (req);
    return req;
}

//Make the XMLHttpRequest Object
var http = createRequestObject();

function sendRequestTwo(method, url, head1){
    head = head1
    if(method == "get" || method == "GET"){
        var myDiv = document.getElementById('loadingDiv');
        myDiv.className = "showClass";

        http.open(method,url);
        http.onreadystatechange = handleResponseTwo;
        http.send(null);

    }
}

var head; //divs name

function handleResponseTwo(){
    if(http.readyState == 4 && http.status == 200){
        var response = http.responseText;
        if(response){  
            document.getElementById(head).innerHTML = response;
            var myDiv = document.getElementById('loadingDiv');
            myDiv.className = "hiddenClass";
        }
    }      
}

Answer №2

At the moment of invoking sendRequestTwo, add the text Loading to the Header div.

Answer №3

Without knowing the specifics of your HTML structure, one suggestion could be to include a loading message within the element with the id="head".

By doing this, when you update the content using innerHTML, the loading message would seamlessly transition into the new content. If there are any additional criteria or specifications needed, feel free to provide more details.

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

Is there a way for me to retrieve information from a different website using a URL, similar to how Digg's submit button works

Currently, I am in the process of developing a website with the cakePHP framework. As a beginner in PHP and web programming, my goal is to implement a feature similar to Digg's submit button. This functionality would involve inputting a URL, which the ...

Filter out any empty properties in JavaScript ajax formData

Need help with excluding empty fields from form data when sending via JavaScript Does anyone know how to prevent empty fields[] from being included in the formData sent through JavaScript? Desired Header Output fields[name]: name fields[phone]: phone ...

Issues with removing options from Autocomplete persist in React MaterialUI

Currently navigating the world of ReactJS and experimenting with Material UI's Autocomplete component. The challenge lies in managing a complex data structure where options are dynamically generated based on user selections, but removing previously se ...

Navigating the dynamic components in Vue using dynamic routing

I'm currently developing an application that helps users manage maintenance tasks. I have successfully created a component to display all the data stored in an array of objects. However, I am facing a challenge in redirecting users to different pages ...

Unable to access cross-domain ASMX Web Service on Internet Explorer 11 due to CORS restrictions

I am facing an issue with my ASMX Web Service - I can consume it from jQuery's $ajax in Chrome, but not in Internet Explorer 11. After learning about CORS limitations, I disabled it on the service by adding these lines to the web.config: <add nam ...

The dreaded Heroku Node.js error H10 strikes again: "Application crashed"

I recently embarked on my journey to learn NodeJS and attempted to deploy it on Heroku. However, when I used 'heroku open,' the following error log appeared: 2020-10-08T14:19:52.778660+00:00 app[web.1]: at Module.load (internal/modules/cjs/loa ...

Building a table from JSON using only JavaScript.orGenerate a

I am working with a dynamic Json containing multiple keys that may vary. Here is an example: Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}] My goal is to create a table with the headers (num, name, phone) Is there a w ...

Component failing to refresh with each key modification

My understanding is that adding a key attribute to a component should make it reactive when the key changes. However, with a v-navigation-drawer from Vuetify, this doesn't seem to have any impact. I've tried making arbitrary changes to the logge ...

Sending a form using Ajax and jQuery

I have created a login form using ajax (jQuery), but I'm facing an issue where the user's email address is not remembered after submission. This means that every time the user logs in, they have to re-enter their full email address instead of it ...

Retrieving specific elements in JavaScript from a JSON file

I am attempting to extract information from a JSON file with the following data: [3000,2500,6000,2200,5000,1300]. The file is named data.txt. To achieve this, I initialize an empty array in my code. Subsequently, I utilize the $.getJSON function by passi ...

Troubleshooting issues with Three.js and .obj file shadows

I've been diving into learning Thee.js, and while it's fairly straightforward, I've hit a roadblock with getting shadows to work. Despite setting castShadows, recieveShadows, and shadowMapEnabled to true in the appropriate places, shadows ar ...

What is the best way to use ajax to send a specific input value to a database from a pool of multiple input values

Welcome everyone! I'm diving into the world of creating a simple inventory ordering site, but am facing a roadblock with a particular issue: Imagine you have a certain number (n) of items in your inventory. Based on this number, I want to run a &apos ...

What is the best way to handle the select event for a jQuery UI autocomplete when there are images involved?

Looking for help with creating an autocomplete feature with images on this jsfiddle. Despite trying to capture the event when a user selects an image, it doesn't seem to work properly: $("#input").autocomplete({ //source: tags, so ...

Insert a new HTML element only if it is not already present

<p id="main_class"> <span class="new_class"></span> </p> In this code snippet, I am attempting to append <span class="new_class"></span> to the element with the id of main_class. If the span element with the class o ...

Pass the identification of a particular card to the following route in order to retrieve data using that specific id in nextjs

[]Hello! I am currently working on fetching data from an API and using the map function to display the retrieved data. My goal is to extract more details about a specific piece of data by taking its ID and passing it to another page. The issue arises in my ...

How can I display different data values on each individual circle counter, rather than all circles showing the same data?

Hey there! I'm trying to get my circular counters to display the counter value that I specify in their class and data-percent. However, currently all four counters are only showing the data from the first counter, even though I've set different d ...

Connecting Websockets in AngularJs for Message Binding

I've hit a roadblock with my mini project, and I have a hunch it's something simple... My challenge is binding websocket messages to an Angular datamodel, but I can't seem to make it work... Here is my controller and some HTML to display t ...

What is the best way to add multiple rows using a parameter in SQL?

My goal is to insert multiple rows in SQLite using the ionic framework. Inserting a single row works fine, as does running the following query: INSERT INTO categories (category_id, category_name, category_type) VALUES (1,"test",1),(2,"test again", 2); ...

When working with AngularJS routing, utilize a function for the templateUrl to dynamically load the appropriate template

Can a function be used as the templateUrl in angularjs routing? The $routeProvider official documentation states: templateUrl – {string=|function()=} Check out the $routeProvider official documentation here In javascript, a function is typically def ...

Jquery Ajax is failing to transmit the authorization header

Attempting to set up basic authentication using Jquery Ajax. Adding an authorization header to the ajax request as shown below. $.ajax({ headers: { "authorization": "basic 123456", }, crossDomain: true, type: "POST", contentTyp ...