Let’s suppose there’s a page implemented with AngularJS.
Ideally the frontend (Angular app) and backend (Web services/API/ call it whatever you like) should be 100% separated from each other which means that frontend project doesn’t have access to database at all. And that’s what I want to achieve.
Let’s say we’re rendering product list. The workflow is:
- request and render HTML template (including JS code)
- Angular app runs
- Angular loads dynamic data (products data to show the list) and put it into the template.
We’ve made 2 requests so far (excluding js/css/images etc.) which is fine. Simple, effective, just great.
And that’s what more or less is shown in tutorials/guides. But that’s not the reality. What I’m wondering is what about small pieces of data that are rendered across whole app layout but have to be retrieved from database.
Exmaples of such data are:
- usename of logged in user in top right corner
- menu with categories on the side bar
- even
<select>
options in forms are often loaded from database (categories again for example)
For me it doesn’t make sense to make a request to backend for each of these pieces of data because it makes a lot of http requests to make on every page refresh/init
How to deal with it?
2
At a super-high level, there’s exactly two ways to mitigate this problem:
1) Allow “batch” server requests, so you can get all these random bits of data in one round-trip. This seems appropriate for all the little lists of categories you need to put in side bars and form fields.
2) Cache information on the client so you don’t have to re-request it for every page. In particular, the username could easily be part of whatever session id/token/cookie/thingy you use to keep the user “logged in”, and categories for the side bar are probably going to be the same on most pages.
As James said, there is some risk of premature optimization, but reducing the total number of server hops is almost always a performance win (when the server isn’t doing anything besides fetching bits of pre-computed data for you).
5