Blog>
Snippets

Improving First Contentful Paint (FCP) in Vue.js 3

Create an example where critical CSS is inlined and render-blocking requests are minimized to enhance the First Contentful Paint, which is a key SEO performance metric.
// Inline Critical CSS in your index.html or entry HTML file
<head>
  <style>
    /* Critical CSS styles go here */
  </style>
</head>
This code represents the HTML where you would inline your critical CSS. It should be placed directly in the head of your HTML file to ensure it loads quickly.
const { defineAsyncComponent } = Vue;

// Use async components for non-critical parts of the app
const AsyncComponent = defineAsyncComponent(() =>
  import('./components/AsyncComponent.vue')
);

export default {
  components: {
    'async-component': AsyncComponent
  }
};
Here we use Vue's `defineAsyncComponent` to create an asynchronous component. This delays the loading of this component until it's needed, which reduces the initial load time and can improve FCP.
import { onBeforeMount } from 'vue';

export default {
  setup() {
    onBeforeMount(() => {
      loadScript('https://example.com/non-critical-script.js');
    });
  }
};

function loadScript(src) {
  const script = document.createElement('script');
  script.src = src;
  script.defer = true;
  document.body.appendChild(script);
}
This code shows how to defer the loading of non-critical scripts in a Vue.js component by appending them to the body only before the component is mounted, using Vue's composition API.