Loading icon disappearing upon page refresh using window.location.reload()

After loading a javascript function on my page, I wanted to add a loading icon to show the user that something was happening. The loading icon worked initially, but disappeared as soon as the page finished loading and did not reappear during subsequent reloads.

I needed the loading icon to only hide after the page had completely reloaded.

Below is the snippet of code I used:

<script type="text/javascript>
$(document).ready(function () {

    (function () {
        if (window.localStorage) {
            if (!localStorage.getItem('firstLoad')) {
                localStorage['firstLoad'] = true;
                window.location.reload();
            }
            else
                localStorage.removeItem('firstLoad');
            $("#loaderbox").hide();
        }
    })();
});
</script>

Here is the code for the loader icon:

<div id="loaderbox">
<div class="loader_bg"></div>
<div class="loder_in">
    <div class="loader_wrapper">
        <div class="preloader-wrapper big active" style="width:102px;height:102px;">
            <div class="spinner-layer spinner-blue-only">
                <div class="circle-clipper left">
                    <div class="circle"></div>
                </div>
                <div class="gap-patch">
                    <div class="circle"></div>
                </div>
                <div class="circle-clipper right">
                    <div class="circle"></div>
                </div>
            </div>
        </div>
        <div class="im_wrapper" style="left:6px;"><img src="/static/images/key.png" alt=""></div>
    </div>
</div>

Answer №1

The problem lies in the fact that

window.location.reload();

does not halt the script execution.

This means you effectively have:

window.location.reload();
$("#loaderbox").hide();

resulting in your loader box being hidden prematurely, even before the reload is completed (especially if it takes a few seconds, which is typical otherwise you wouldn't be using a loader / noticing its absence).

You can verify this behavior in the console by running:

window.location.reload(); alert("before reload");

which will display the alert before the page reloads.

To fix this issue, add a return statement immediately after the reload() to prevent further execution (or adjust the placement of the .hide() so it doesn't always execute after the if-else block.

$(document).ready(function () {

    (function () {
        if (window.localStorage) {
            if (!localStorage.getItem('firstLoad')) {
                localStorage['firstLoad'] = true;
                window.location.reload();
                return false;
            }
            else {
                localStorage.removeItem('firstLoad');
                $("#loaderbox").hide();
            }
        }
    })();
});

Answer №2

Once the DOM is fully loaded, the function $(document).ready will be activated.

Utilize this to run a function after all content has finished loading (including images, etc).

$(window).on('load', function() {
 console.log('All assets have been loaded')
})

Answer №3

A much more efficient approach is to employ JavaScript in order to identify when the webpage has completed loading and then eliminate the loading icon.

$(document).ready(function () {
    $("#yourImageId").remove();
});

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

Various Utilizations through a Single Alexa Skill

In my skill SkillIntent, when asked about a specific game, it provides the description of that skill. Now, I want it to also inform WHO has that Skill when asked differently. Below is the code snippet: 'use strict'; var AlexaSkill = require(&a ...

Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style. function printContent() { var divContents = document.getElementById("terms").innerH ...

Using AJAX to populate a dropdown menu with an array in PHP

I am working on a functionality where I have two drop-down boxes. The first one should select the category, triggering an AJAX call to a PHP file that fetches the appropriate subcategory array and populates the second drop-down. Check out the code snippet ...

Basic asynchronous JavaScript and XML (AJAX) call

I am currently learning about ajax and experimenting with a script that involves extracting information from a JSON object and displaying it on the document. Below is an example of the JSON file named companyinfo.json: { 'id':1, 'name&apos ...

Issues with Node.js and Socket.io: Receiving error "Cannot read property 'on' of undefined"

I've encountered an issue while trying to establish a websocket connection using socket.io and node.js. Here is the setup I'm working with: Operating System: Windows 7 Node version: 6.9.2 NPM version: 4.0.5 Packages: "express": "^4.14.0" "soc ...

Attach the div element firmly to the bottom of the webpage

I'm trying to place a second div under one with position absolute, but the two divs have different widths. The top div is centered and positioned absolutely, while the bottom div should span 100% of the width. Any suggestions on how to achieve this? ...

How to use jQuery to hide the submit button once it's been clicked for processing and update the form's action attribute

I am currently facing an issue and would greatly appreciate any assistance. The situation is as follows: I have a form with a text box and a submit button. The process-page.php file contains a PHP script that queries my database for user information and p ...

Obtain an array from an Ajax request using jQuery Datatables

I have integrated the jQuery DataTables Select plugin into my project to enable the selection of multiple rows from a table and storing their data inside an array. Subsequently, I am attempting to make an Ajax Request to pass this array to another PHP file ...

Load an image dynamically within a JavaScript function

I'm currently utilizing a Javascript photo viewer plugin (found here: http://www.photoswipe.com/). My goal is to dynamically update the photos connected to the plugin as the user swipes through different images. To achieve this, I am using a Javascri ...

What are the steps to utilize chrome.tabs.onUpdated.addListener?

I am currently working on a Chrome extension where I need to display an alert() showing the page URL whenever the user switches tabs or enters a new URL in a tab. However, my current implementation is not functioning as expected: chrome.tabs.onUpdated.ad ...

Embed a static label inside an input field that remains constant even while text is inputted, without using a placeholder. Crafted using HTML,

Take a look at the screenshot below - what you see on the left side is my current setup, while on the right side is the desired outcome achieved without any plugins or HTML5 attributes The left side scenario occurs when I have 2 input fields - one with th ...

CSS Novice in need of expertise with layout arrangement

Similar Question: Nesting Divs Tutorial I'm relatively new to CSS as I've been using tables in my HTML projects for quite some time now. I am currently trying to understand how to nest or stack divs inside the content section of a 3-column l ...

Position an HTML canvas at the very top of the webpage

Can someone help me figure out how to align a canvas element to the very top (0, 0) of a webpage? I attempted using margin: 0; padding: 0px;, but it didn't work. There always seems to be some white space at the top that I can't eliminate. ...

Retrieve geographic coordinates based on location name using Google Maps API

Is there a way to obtain the coordinates of a specific area by entering its name using the Google Maps API within the .NET framework? For instance, if I search for Washington, DC, USA, can Google Maps provide me with the coordinates of that area? Are the ...

jQuery slider triggering a function with a consistent delay of 1 until the handle is released

I've been trying to figure out this issue for a while now and haven't found a solution yet. If you take a look at my project here, you'll see that the values at the top don't update correctly until the handle is released. I've been ...

Verify whether the element retains the mouseenter event after a specified delay

I recently implemented some blocks with a mouseenter and mouseleave event. <button onMouseEnter={this.MouseEnter}>hover</button> MouseEnter(e) { setTimeout(() => { // Checking if the mouse is still on this element // Pe ...

My React component seems to be unable to locate and process my CSS file

I am encountering an issue where my React Component is not recognizing my CSS file. Here is the code snippet from my React component: import React, { Component } from 'react'; import './Jumbotron.css'; class Jumbotron extends Compone ...

Sequencing and fulfillment of promises in a job queue using Promise.race

Currently, I'm grappling with the concepts of job queue and promise resolution in Javascript. While going through Nicholas Zakas' book "Understanding ECMAScript 6", I came across a code snippet regarding Promise.race() that has left me puzzled: ...

Creating a complete webpage using HTML

Is there a method to load an HTML file and execute the embedded javascript to create a complete HTML page programmatically similar to how browsers do? Edit 1 - I am working on an application where I need to extract data from an HTML page on a remote websi ...

Unclear value of button when being passed

In my Welcome.html file, I am attempting to send the value of a button to a function that simply logs that value. This function is located in a functions class that has been imported into my welcome.ts file. <ion-content padding id="page1"> <h1 ...