Blog>
Snippets

Lazy Loading Components for Improved Mobile Performance

Demonstrate using Vue 3's async components feature to lazily load components on demand, which can lead to improved performance on mobile devices.
import { defineAsyncComponent } from 'vue';

// Define an async component loader
const LazyComponent = defineAsyncComponent(() =>
  import('./path/to/YourComponent.vue')
);

export default {
  components: {
    LazyComponent
  }
};
This code snippet shows how to import 'defineAsyncComponent' from Vue 3 and use it to define a lazy-loaded component. 'LazyComponent' is a placeholder name that represents the async component. The actual component to be lazily loaded is referenced by './path/to/YourComponent.vue'. When 'LazyComponent' is used in a template, Vue will load the component on demand, which can significantly improve mobile performance as components are only loaded when needed.
<template>
  <div>
    <!-- Use lazy-loaded component conditionally -->
    <LazyComponent v-if='shouldBeLoaded' />
  </div>
</template>

<script>
// Import the lazy component definition
import LazyComponent from './lazy-component-definition';

export default {
  components: {
    LazyComponent
  },
  data() {
    return {
      // Data property that determines whether to load the component
      shouldBeLoaded: false
    };
  },
  mounted() {
    // Simulate some condition to load the component, e.g., scrolling into view
    window.addEventListener('scroll', () => {
      if ( /* some condition */ ) {
        this.shouldBeLoaded = true;
      }
    });
  }
};
</script>
This snippet is part of a Vue component file. In the <template> block, the 'LazyComponent' is used with a 'v-if' directive, so it will only be rendered and loaded when the 'shouldBeLoaded' data property is true. In the <script> block, the 'LazyComponent' is imported and added to the component's local registration. The mounted lifecycle hook is used to add an event listener to the window 'scroll' event. When a certain condition (e.g., the component scrolled into view) is met, the 'shouldBeLoaded' property is set to true, triggering the lazy loading of the component.