Mari Selvan
Mari Selvan

Reputation: 3802

Ember JS : Lazy load Model data

I'm trying to render ember model data which has more than 1000 records. This will take more than 2 min to finish the rendering part.

So, I have a plan to optimize it. I want to load the first 100 records in the first time. Once they go to the end then I need to load the second 100 records.

How can I do that?

Upvotes: 1

Views: 480

Answers (1)

mistahenry
mistahenry

Reputation: 8724

Retrieving pages of data

The concept is paging and depends on how your backend handles paging. But in the generic case, something like:

let result = this.store.query('post', {
  limit: 10,
  offset: 0
});

once processed by the backend would result in a query to a relational database like:

SELECT * FROM post LIMIT 10 OFFSET 0;

So, you will need to keep track of the current page you are showing. Each time you want to fetch a new page, you will simply increment your offset by page * limit where page is the current page index. So the next query when page = 1 would be:

let result = this.store.query('post', {
  limit: 10,
  offset: 10 // 1 * 10
});

It's probably a good idea for you backend to return the total result count, which you can access via some kind metadata key on your JSON responses (or however you want since it depends on the way your backend speaks collections). This way you know when to stop trying to fetch the next page.

UX around retrieval

You will need to choose whether you want to do simple paging, which supplies a next and previous button that the user clicks on to retrieve the next / previous page. Probably best UX to manage the page with query params so that the forward/back buttons in the browser move pages and refreshing does not lose the page. You should also disable / enable the previous and next buttons when there are no pages to fetch in either direction.

Pros

  • easy to develop
  • user never loses their place
  • since only ever showing one page at a time, no memory / performance concerns

Cons

  • users have to click buttons and may choose not to / not realize how

Addons

The alternative would be using infinite scrolling (a la Facebook news feed). You must pay attention to the scrolling position to know when to fetch the next view (which requires math around the sizes of the current items). Alternatively, you evaluate whether item n - 2 or something like that is in the view port and then prefetch the next page.

Pros

  • users never think about paging and continue seeing new content with ease

Cons

  • horrible for returning to ones spot on page change / refresh
  • horrible for searching
  • requires a great deal of attention to the amount of data you are showing or else you will run into overconsumption of memory and performance degradation.
  • more difficult to write since you must handle scrolling events, view port detection, etc

addons

Upvotes: 5

Related Questions