Tips for implementing a preloader to load before your VUE.JS page begins loading

I'm facing an issue while setting up a preloader. Instead of running the preloader first, it starts downloading a bunch of CSS/js files, which is not ideal. This problem is more prominent on slower connections like FAST 3G or SLOW 3G.

After researching, I found examples of using vue routing for preloading, but I'm using Vue with flask, so the routing method might not work for me, as far as I know.

Is there a way to configure it so that the preloader loads first and then background loading of other resources starts?

For the preloader, I am using the Vue plugin Vue-loading-overlay.

Sharing a snippet of my code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
  <div id="app">
    <vue-topprogress ref="topProgress" :color="'#1d1d25'"
                     :height="5" :errorColor="'#f81732'"/>
    <loading :active.sync="isLoading"
        :is-full-page="true" :opacity="1">
      <img src="../assets/images/testGif.gif" alt="this slowpoke moves"  width=250/>
    </loading>
  </div>
</template>
<script>
  import Loading from 'vue-loading-overlay';
  import 'vue-loading-overlay/dist/vue-loading.css';

  export default {
    name: 'index',
    components: {
      Loading,
    },
    data() {
      return {
        isLoading: true,
      };
    },
    mounted() {
      document.onreadystatechange = () => {
        if (document.readyState === 'complete') {
          this.isLoading = false;
        }
      };
    },
  }
</script>

Answer №1

Two possible solutions come to mind: using an async route or an async component.

Async route

In the routes.js file, we set up the main route / to load a simple LoginPage component from the main JS bundle file. Additionally, we define a /app route with an async component that will only be loaded when a user accesses the /app route. By using a comment with webpackChunkName, we instruct Webpack to compile that component into a separate file with the specified name.

routes.js

import LoginPage from '../pages/login-page'

const routes = [
 {
  path: '/',
  component: LoginPage
 },
 {
  path: '/app',
  component: () => import('../pages/app-wrapper.vue' /* webpackChunkName: "page--app-wrapper" */),
  children: [
   // child routes
  ]
 }
]

In the login-page component, you can perform tasks like loading configuration data via AJAX and then navigate to the /app route.

Async component

Another approach is to utilize a dynamic component. Initially, it can be a simple loaderComponent, and upon completion of loading, it transitions to an appWrapperComponent that is defined in a larger chunk file.

<template>
  <div :is="componentName"></div>
</template>
export {
  data() {
    componentName: 'loaderComponent'
  },
  components: { loaderComponent },
  mounted() {
    this.$axios('/api/config.json') // just an example of loading data
    .then(config => {
      this.$root.config = config; 
      this.componentName = 'appWrapperComponent'; // update component name
    });
  }
}

To ensure the functionality, we need to make the appWrapperComponent async.

Vue.component('appWrapperComponent', () => ({
    component: import('../pages/app-wrapper.vue' /* webpackChunkName: "pages--app-wrapper" */),
    delay: 200,
    timeout: 5000
}));

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

Using C# Razor Pages to send checkbox values via AJAX requests

In my model class, I have the following: public class DataModel { public bool Display { get; set; } } After deserializing a FormData object to a JSON object, I am posting the value from a checkbox like this: this.FormToJSON = form => { const ...

create a PDF document that contains interactive input fields which can be modified using Angular

My goal is to generate an editable PDF using JavaScript and AngularJS, allowing users to input data into text fields on the document. However, when I download the PDF, the text fields are not editable. Here is a snippet of the code: var opt = { margin ...

Handling MySQL insertIds and errors in Node.js using MySQL is a crucial aspect of

I am struggling to handle errors and retrieve the insertId after creating a new row in my database using code from the official page of mysqljs/mysql. How can I modify my code to achieve this? var post = {deviceImei: deviceInformation.deviceImei, created_ ...

What could be the reason for the styled-jsx not applying the keyframe animation?

When attempting to add the animation separately without any conditions, the transition fails to be applied. Changing the quotation marks to backticks for the animation property also did not work. Is there a way to apply both the animation when clicked is ...

Is there a way to determine the path of the fetch function within a PHP file?

I am using a JavaScript function to retrieve data from the backend server async getAllExpensesByUser() { let response = await fetch("router.php/getAll"); return response.json(); } My question is, how can I retrieve the path "/getAll ...

Angular Dynamic Table Column Adaptor

Recently, I came across the adpt-strap table lite and decided to experiment with it. Here is the JSfiddle link for the project I was working on: http://jsfiddle.net/cx5gm0sa/ My main goal was to dynamically hide or show a column. In my code, I added $scop ...

Building on the functionality of AngularJS, a directive scope can be established to access and modify

Can a directive accept and utilize a parameter as its scope value? For instance: angular .module('app', []) .controller('CTRL', function($scope) { $scope.some_value = { instance1: { key1: 'value11', ...

Refreshing an external file in Node.js at regular intervals

Seeking guidance on loading external files in node. I'm currently working with an external JSON file that houses some configuration settings, and this file gets updated by an outside process every 10 minutes. How can I automate the reloading of this ...

Processing data from a Buffer object using the .map() method and sending it as props to a component

As I work on my application, I encounter a challenge when dealing with a Buffer object that contains data from a file. My intention is to render the component Bar for each byte in this buffer and pass the byte as a prop. However, I am facing an issue with ...

Easy selector for choosing jquery css backgrounds

Here is a simple background selector that I created. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <hea ...

Leverage the power of Reactjs to add hover effects to a mapped

I am facing a challenge in styling the ListItem on hover. The issue arises when the list is dynamically generated, causing all list items to change style simultaneously when hovered over. How can I target only one element for styling? Below is the code sni ...

Numerous access points within Vite

I am currently working on a Vue2 project that uses Webpack, and I have decided to make the switch to Vite. Within my webpack.common.js file, there are multiple entry points defined: module.exports = { entry: { appSchool: './resources/scho ...

Identifying all Images with JavaScript, Including Asynchronous Ones

Is it possible to use JavaScript to identify all images within a document, even those that are loaded asynchronously (possibly after the DOM is fully loaded)? I am interested in developing a function that can determine if Google Analytics has been loaded ...

A guide to increasing a loop counter in Vue

Having trouble looping through a specific group of objects in a multi-object array? Take a look at the code below: <template> <div> <h1>My Test App</h1> <button v-on:click="getHockeyData">Get Team Data< ...

Does vee validate only apply to the initial field?

I've gone ahead and created two modals, one for logging in (loginModal) and another for registering (registerModal). Users have the ability to seamlessly switch between the two. However, I've encountered an issue with the "VeeValidate" plugin. I ...

When working with angular.js and angular-sanitize.js, the src attribute is removed from JSON HTML data

I'm new to Angular and I'm really enjoying learning how to work with it. Currently, I have a simple JSON file that contains text structured like this: "gettingstarted":{ "title":"Getting Started", "content":"<img ng-src='i ...

Advantages of placing script src tags at the top of the body versus placing them at the bottom of the body

I've heard that it's best to place the script tags right before the closing body tag. However, when I follow this advice, my angularJS expressions don't seem to compute correctly for some reason. When I place the script tags in that location ...

Tips for arranging the items within the slider according to the specified direction (rtl, ltr) in the Owl Carousel slider for Angular

Is there a way to dynamically change the direction of the owl-carousel-o angular slider based on the selected language? Currently, I have set rtl: true in the owl-carousel configuration during initialization. However, when the user switches to a different ...

Deleting outdated files in a temporary uploads directory - NodeJS best practices

My process for removing old files from a tmp upload directory involves the code below: fs.readdir( dirPath, function( err, files ) { if ( err ) return console.log( err ); if (files.length > 0) { files.forEach(function( file ) { ...

The function is missing a closing return statement and the return type does not specify 'undefined'

It seems like the function lacks an ending return statement and the return type does not include 'undefined'. In a recent refactoring of the async await function called getMarkets, I noticed that I had mistakenly set the return type as Promise: ...