question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Initial Load Taking Too Long

See original GitHub issue

This may be a result of having too much content (1200 pages), but on the initial load of “The Latest” content - it can sometimes take several minutes, and a couple refreshes to actually see the newest content using content. Locally it happens in a matter of seconds, but in production (SSR full static) - it takes too long…

My current implementation:

    async fetch() {
      this.latestArticles = await this.$content('articles').sortBy('published', 'desc').limit(5).fetch()
      this.latestAnalyses = await this.$content('analysis').sortBy('published', 'desc').limit(5).fetch()
      this.latestBlog = await this.$content('blog').sortBy('published', 'desc').limit(10).fetch()
}

and then in a computed property, I mash them together like so:

      latestContent() {
        return this.latestArticles.concat(this.latestAnalyses,this.latestBlog).sort(function(a, b) {
          var keyA = new Date(a.published), keyB = new Date(b.published);
          // Compare the 2 dates
          if (keyA < keyB) return 1;
          if (keyA > keyB) return -1;
          return 0;
        })
      }

I’m pretty sure it’s not the latestContent, because my $fetchState.pending block runs throughout that entire time.

Again, this is for target: static, so I would assume even during the build process there should be something there at first, yes?

Issue Analytics

  • State:open
  • Created 3 years ago
  • Comments:8 (7 by maintainers)

github_iconTop GitHub Comments

1reaction
azrikaharcommented, Sep 30, 2020

No worries. There’s nothing wrong with using fetch() to get the data on client side when they visit the page, and this is definitely a valid use case depending on situations. However, I do believe you will benefit more with using asyncData() without having to wait for the fetch() in this particular scenario 😃

And I’ve never really understood difference between asyncData and fetch. They seem the same, with the latter being the more modern up-to-date approach.

Rest assured I was not sure of their difference in the beginning as well haha. I might be oversimplifying here, but I think we can think asyncData() as being done before the page is served to the user. Which means what ever is done in there, won’t be done on the client side at all. Though this is true for SSR, it behave slightly different when you are using full static. When you run nuxt generate command, Nuxt have a crawler that will go through each pages/links and run the asyncData() once and generate the final HTML files.

As for fetch(), the default behaviour is running it once on the server unless you disable it using fetchOnServer: false (reference) in SSR. However in your case, you are using full static, so it means it will only ever run on client side. This means whenever someone visits the homepage, they will fetch from the built API that is served by your generated files, do 3 await calls then run sort over each item in the array which can be pretty taxing in terms of processing.

Do note that I mentioned *built API files, which means they are static and are baked in to your dist folder, and the fetch() are technically fetching from the built static files, not directly from your GitHub repo. So when you mentioned you want to upload one file change and not have to rebuild the entire site, it will not be possible with this approach. With that said, many static site hosting services like Netlify does provide github repo integration, so you don’t have to worry about manually rebuilding the site. You just need to push a commit and the rebuild is done automatically for you.

Sorry if the explanation is too much. Just try out the proposed solution below and see how it is for you.


Proposed solution

I am going to translate your existing code to asyncData() here, so I’ll try to mimic your code since I can’t truly see the whole source code. Hope it’s roughly accurate here.

Your current code

<template>
  <template v-if="$fetchState.pending">
    <!-- Show the spinner here -->
  </template>
  <template v-else>
    <!-- Loop through **latestContent** computed array here to show the articles -->
  </template>
</template>

<script>
export default {
  data() {
    return {
      latestArticles: [],
      latestAnalyses: [],
      latestBlog: [],
    }
  },
  async fetch() {
    // the 3 await $content calls here
  },
  computed: {
    latestContent() {
      // your sorting code here
    }
  }
}

Using asyncData() for full static without any fetching needed on client side

<template>
  <div>
    <!-- Loop through **latestPosts** data array here to show the articles -->
  </div>
</template>

<script>
export default {
  async asyncData({ $content }) {
    const results = await Promise.all([
                                     $content('articles').sortBy('published', 'desc').limit(5).fetch(),
                                     $content('analysis').sortBy('published', 'desc').limit(5).fetch(),
                                     $content('blog').sortBy('published', 'desc').limit(10).fetch()
                             ])
    const unsortedPosts = [].concat(...results)
    const sortedPosts = unsortedPosts.sort((a, b) => {
          const keyA = new Date(a.published), keyB = new Date(b.published);
          // Compare the 2 dates
          if (keyA < keyB) return 1;
          if (keyA > keyB) return -1;
          return 0;
        })
    return { latestPosts: sortedPosts }
  },
}

The latestPosts returned in asyncData will be added to the data() option, that’s why we don’t even need to specify data() like in fetch example anymore. And since you are doing the sorting during build process, your client side never needs to run any fetching or sorting and should be able to instantly see the posts in your homepage.

Further explanation:

Would you mind giving this solution a try? Feel free to change the variable names I used to what you see fit.

0reactions
Tahulcommented, May 10, 2022

Hello 🙂

Has your issue been fixed?

I think this is still relevant for v2, so I’m keeping this open, would love to see performances benchmarks between v1 and v2!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Re: Slow initial load - Microsoft Power BI Community
Every single initial page load (page or drillthrough) has some lag. After I've opened all the pages, I close the browser en reopen...
Read more >
Website Initial Load time is too long - Frontity Community Forum
Hi, We just converted our WordPress site to frontity. But the initial load time is too long. Can anyone suggest that what I...
Read more >
How to Reduce React App Loading Time By 70% | By Nilanth
When the app grows larger and larger, the performance might deteriorate. Particularly the initial loading time of the app will be affected more....
Read more >
Slow Initial Page Load | WordPress.org
I am using Shared Hosting and I was wondering if this could be the reason that the initial load time is slow (usually...
Read more >
Improving Angular initial load time - DEV Community ‍ ‍
A good performance monitoring solution is to check the network tab when initially loading your page. Check the API requests. Maybe you have...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found