Display a loading screen to the user while Vue lazy loads the content

I am currently implementing lazy loading features for my single-page application using Vue.js and Laravel Mix 5. I am looking for a way to display a loading page to prevent the app from appearing unresponsive while new pages are loading.

I attempted to add the following code:

<template>
<div>
    <!-- header -->
    <transition 
        enter-active-class="animated fadeInDown"
        leave-active-class="animated fadeOutUp"
        mode="out-in"
    >
        <router-view name="header"></router-view>
    </transition>
    
    <!-- body -->
    <transition 
        enter-active-class="animated fadeIn"
        leave-active-class="animated fadeOut"
        mode="out-in"
    >
        <router-view></router-view>
    </transition>
    
</div>
</template>

Initially, I expected this code to trigger a fade-out animation while waiting for the new page to load. However, in reality, the screen does not animate as expected and the app seems unresponsive (even though buttons still function).

My proposed solution is that when a user clicks to navigate to a new page, I want to hide or remove the current page to indicate that something is happening behind the scenes and prevent users from repeatedly clicking buttons, thinking the website is unresponsive.

Answer №1

After thorough research, I finally discovered the solution to my problem.

Firstly, using Vuex to pass variables or information is necessary. Then, simply integrate it into the router function like so:

router.beforeEach((to, from, next)=>{
  store.commit('setLoading', true)
  next()
})
router.afterEach((to, from)=>{
  store.commit('setLoading', false)
})

In my app.vue file, I added the following code:

<template>
<div>
    <!-- header -->
    <transition 
        enter-active-class="animated fadeInDown"
        leave-active-class="animated fadeOutUp"
        mode="out-in"
    >
        <router-view name="header"></router-view>
    </transition>
    
    <!-- body -->
    <transition 
        enter-active-class="animated fadeIn"
        leave-active-class=""
        mode="out-in"
    >
        <loading-page v-if="isLoading"></loading-page>
        <router-view v-else></router-view>
    </transition>
    
</div>
</template>

<script>
    import { mapGetters } from 'vuex';
    import loadingPage from "./views/loading.vue";

    export default {
        components: {
            loadingPage
        },
        computed:{
            ...mapGetters('global',{
                isLoading: 'isLoading'
            }),
        },
    }
</script>

Here is my simple loading screen with a progress bar:

<template>
    <div>
        <!-- page container -->
        <div class="page-content">
            <div class="content-wrapper">
                <div class="content">

                    <div class="card card-body">
                        <div class="progress">
                            <div class="progress-bar progress-bar-info progress-bar-striped progress-bar-animated" style="width: 100%">
                                <span class="sr-only">100% Complete</span>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        
    </div>
</template>

As for my Vuex setup:


export const global = {
  namespaced: true,
  
  // state
  state: {
    isLoading: '',
  },

  // getters
  getters: {
    isLoading: state => state.isLoading,
  },

  // actions
  actions: {

    // change data
    setLoading({commit}, type){
      commit('setLoading', type);
    },
  },

  // mutations
  mutations: {

    setLoading ( state, type ){
      state.isLoading = type;
    },
  }
}

Now, the loading screen will display whenever a user navigates to a page that has not yet loaded in their browser.

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

Tips for displaying a modal to a user only once

I've developed a Flask application that enables multiple users to register and log in. To achieve this, I have incorporated sessions into my code. When new users land on the initial page, they are greeted with a modal introducing them to the platform. ...

Using React to dynamically assign a backgroundImage based on a JSON response

I am having an issue with retrieving data from my Wordpress API and displaying it in my react app. Specifically, I am struggling to set the post's featured image as a background-image for an element. Here is an example of the JSON response: { "id" ...

Finding the correct path for ts-loader with webpack version 2.2.1 within a script

When running the gulp task below, I encounter an error: Module not found: Error: Can't resolve 'app.ts' in 'wwwroot/js/admin' gulp.task("admin:js", function (done) { module.exports = { context: "wwwroot/js/admin", ...

While working with AJAX, the variable value remains static and is not refreshed

My jQuery code successfully calls a REST Service and handles the response in the AJAX Success event. However, I'm facing an issue where the variable "SelectedVal" (document.getElementById('Text1').value) is not getting updated with each cli ...

Transforming a high chart into an image and transmitting it to the server through an ajax request

I am looking for a way to save multiple charts as PDF files on the server using an AJAX call. Each chart is rendered in a distinct container on the same page, and I need to convert them into images before sending them to the server for export. Any assist ...

CSS Testimonial Slider - Customer Feedback Display

I'm having some issues with the code below: <div id="box"> <div class="wrapper"> <div class="testimonial-container" id="testimonial-container"> <div id="testimon ...

Using Node http-middleware-proxy and integrating it with Express to communicate with Tomcat server

We have set up our Java application (which is spring based) in a Tomcat container, with the UI modules also running in the same environment. When we access Tomcat directly through http://localhost:8080, a login page is displayed and then a 302 redirect occ ...

Ways to customize a directive to show conditionally with no need for container elements

I have created a basic role-based security directive in angularjs. It's my first attempt at making a directive. My goal is to replace the following HTML: <authorize if-granted="GET_POSTS"> Hello WORLD!!!! {{name}} </authorize> with j ...

Securing a namespace using passport js: A step-by-step guide

Imagine I have set up a specific route with the following namespace: app.use('/registered', userRoute); Recently, I wrote the following passportjs function: app.get('/logged/dashboard', function (req, res) { if (req.user === undefi ...

What steps can be taken to provide accurate information in the absence of ImageData?

Utilizing a JS library to convert a raster image into a vector, I encountered an issue where the library returned a fill of solid color instead of the desired outcome. I suspect that the problem lies within the ArrayBuffer. The process of loading an imag ...

Tips for efficiently saving data using await in Mongoose

Currently, the code above is functional, but I am interested in utilizing only async/await for better readability. So, my query is: How can I convert cat.save().then(() => console.log('Saved in db')); to utilize await instead? The purpose of ...

When zooming out, Leaflet displays both tile layers

I'm currently working on integrating two tile layers along with a control for toggling between them. Below is the code snippet I am using: const layer1: L.TileLayer = L.tileLayer('http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png', { ...

Synchronous execution of functions in Node.js

I need to ensure that func2 is only called after func1 has completed its execution. { func1(); func2();// } However, the issue arises when func1() starts running and func2() does not wait for it to finish. This leads to a runtime error as func2() require ...

Utilizing the power of Koa.js in conjunction with MongoDb for seamless development

Having an issue, or maybe just lacking some knowledge here. The question is pretty straightforward - I have this code: router.get('/', (ctx, next) => { MongoClient.connect(url, {useNewUrlParser: true}, function (err, db) { if (err) th ...

Executing a JavaScript function within a PHP echo statement

I am completely new to working with AJAX and PHP echo variables or arrays. However, I have managed to successfully display images on my website by passing variables from AJAX to PHP and back. The only problem I am encountering is when I try to call a Javas ...

Learn how to configure your Angular uib-typeahead to display suggestions as soon as the model is bound

Currently, I am setting up a search functionality. Whenever a user inputs a character into the search box, I use the ng-change event to call an API, retrieve the model, and bind it to uib-typeahead. My goal is for uib-typehead to immediately start suggesti ...

Which one should I use: ng-repeat or ng-options?

I am looking to display JSON data in a dropdown list, and I have two options to choose from. The first option is using ng-repeat, while the other option is ng-options. Using ng-repeat: In the HTML file: <select> <option ng-repeat="prod in testA ...

No styles are appearing on a specific element after running a specific jQuery function on that element within a Vue page

I recently integrated JQuery-AsRange (https://github.com/thecreation/jquery-asRange) into my vue.js project. Everything functions as expected within the .vue page, however, I am facing an issue with css styling not being applied. The css styles should be ...

Passport Authentication does not initiate a redirect

While working on a local-signup strategy, I encountered an issue where the authentication process against my empty collection was timing out after submitting the form. Despite calling passport.authenticate(), there were no redirects happening and the timeo ...

Obtaining Asynchronous JavaScript responses with Selenium Webdriver

We recently integrated an asynchronous JavaScript call into our website. I am currently working on configuring Selenium Webdriver to pause and wait for a response from this particular call. The event listener code snippet is as follows: $(document).on("a ...