loading...

Defer Rending of Component Data Loading with Fastboot and Ember.js

scottamesmessinger profile image Scott Ames-Messinger ・1 min read

We do the fast majority of our data loading in our components. We also use Fastboot which, by default, only awaits for promises to resolve that are returned in the model hook.

Because all our data requests go through a central service, we're able to keep track how many requests are outstanding and then tell Fastboot to stop deferring and begin rendering the page. This isn't the most beautiful solution, but it's worked for us!

export default class ApplicationRoute extends Route {

  model(params, transition) {

    if (this.fastboot && this.fastboot.isFastBoot) {

      // Create a promise we'll resolve when we're done fetching data
      let promise = new Promise((resolve, reject) => {
        let poll = () => {
          later(() => {
            if (this.finder.inFlightRequests.length === 0 && this.query.inFlightQueriesCount === 0) {
              // If we have no more requests, wait until Ember has rendered and then resolve the promise
              scheduleOnce("afterRender", this, resolve)
              return
            } else {
              // Still more outstanding requests, so poll
              poll()
            }
          }, 50)
        }
        poll()
      })

      // Pass the promise to fastboot so it will awai
      // until the promise resolves before rendering
      this.fastboot.deferRendering(promise)
    }

  }
}

Discussion

pic
Editor guide