Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How load component after First Contentful Paint or first elements in Vue.js or Nuxt.js?

My goal is best solution the First Contentful Paint with Vue.js or Nuxt.js

I think the best solution is to load component with import after when the first elements are loaded.

I don't know if is best solution, I would like to hear your opinions.

What is best way to code?

Trying:

The file is loaded with app.js, how load only a time when I set to true?

devtools

<template>
  <h1>Hello World</h1>

  <!-- First content here -->

  <foo v-if="documentLoaded" />
</template>

mounted() {
  document.onreadystatechange = () => {
    if (document.readyState == "complete") {
      console.log('Page completed with image and files!')

      setTimeout(() => {
        this.documentLoaded = true
      }, 2000);

    }
  }
},
components: {
  Foo: () => import(/* webpackChunkName: "component-foo" */ '~/components/foo')
}
like image 387
Adriano Resende Avatar asked Nov 06 '22 18:11

Adriano Resende


1 Answers

You can define when a dynamically loaded component is effectively loaded using import like you said, in conjunction with v-if on the component.

<mycomp v-if="readyStateComplete"/>

//readyStateComplete is a boolean from data.

Setting the boolean to true will trigger the loading, then init and display of the component.

mounted() {
  document.onreadystatechange = () => {
    if (document.readyState == "complete") {
      console.log('Page completed with image and files!')

      // HOW LOAD COMPONENTS HERE?
      this.readyStateComplete = true

    }
  }
},

If you want your component to be loaded the same time as the image, but just displayed after, use v-show instead of v-if.

like image 91
Slim Avatar answered Nov 15 '22 10:11

Slim