DEV Community

Ayowande Oluwatosin
Ayowande Oluwatosin

Posted on

Asynchronous Loading in Vue

Recently, I came across a performance issue on a Vue webpage where the loading time was excessively long. Upon thorough investigation, it became evident that several functions were being loaded simultaneously in the mounted lifecycle hook. While these functions were necessary for the page, it was not essential for all of them to be called simultaneously. This simultaneous loading was causing a slowdown in the page's performance.

To address this issue, one approach is to load specific functions asynchronously. By leveraging the power of async/await, along with Promise and setTimeout, we can achieve asynchronous loading and execution of the required functions within the mounted lifecycle hook of our Vue component. This ensures that the functions are loaded and executed in a non-blocking manner, enhancing the overall performance of the page.

For example,

mounted() {
  this.synchronousFunction();
  this.loadAsyncFunctions();
},

methods: {
  async loadAsyncFunctions() {
    await this.delay(1000); // Delay for 1 second
    await this.asyncFunction();
    await this.delay(2000); // Delay for 2 seconds
  },

  async delay(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  },

  synchronousFunction() {
    console.log('This function is called synchronously');
  },

  async asyncFunction() {
    console.log('This function is called asynchronously');
  },
}
Enter fullscreen mode Exit fullscreen mode

In the code snippet above, we have a mounted lifecycle hook in a Vue component. Inside the mounted hook, we call a synchronous function synchronousFunction() and an asynchronous function loadAsyncFunctions().

The loadAsyncFunctions() method utilizes the async/await syntax to load and execute functions asynchronously. It uses the delay() function, which returns a promise that resolves after a specified delay (in milliseconds). By awaiting the delay() function, we can introduce delays between the execution of different async functions.
The delay method is a utility function that returns a promise which resolves after the specified delay using setTimeout.

The synchronousFunction() is a regular synchronous function that is called immediately.

The asyncFunction() is an example of an asynchronous function that is also called within the loadAsyncFunctions() method. It showcases the asynchronous nature of the function.
Each async function is invoked using await, which ensures that the subsequent function is only called after the previous one has completed.

By using this approach, the synchronous function is called immediately, while the asynchronous functions are executed with delays, allowing for smoother performance and better user experience.

Top comments (0)