Building this kind of one-page apps allows for clean separation between the presentation and API layers. The downside is that it will slow page render times - fetching data after page load means waiting for an AJAX request to complete before displaying anything.
Without changing the entire architecture of the system, how can we bootstrap JSON data server-side and avoid the data roundtrip on every page load?
First, we need to keep track of our objects on the client. We've implemented a simple data repository. It ensures that the same model is passed around instead of instantiating new models each time. This helps prevent unnecessary trips to the server, and makes sure events are bound to the same model instance.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Objects of the same type are stored together in a repository collection.
1 2 3 4
A view requires data before it can be rendered. For example, navigating to artsy.net/artist/hendrik-kerstens (a Dutch photographer who obsessively took pictures of his daughter in all kinds of artificial setups for 20 years) will call the following.
1 2 3 4 5 6 7
1 2 3
You must encode JSON data inside a Rails template, otherwise unicode characters like U+2028 become actual line-endings. This has been discussed here and here. The
j above is an alias for
The Rails view layout calls
show.html.haml template includes the bootstrapped data as a partial.
The generated HTML includes the escaped JSON representation of the artist, which will be parsed client-side when the page loads and inserted into
App.Views.ArtistView will no longer need to fetch the data from the server with an AJAX call.