I'm currently working on a framework named "onecode" that does what you asked for. Currently it lacks documentation, but I have a working project based on it, so it could work for you too. I'm also looking for contributors.
Here's how it works. Almost all code is shared between client and server, including models and views.
- On server, you create a REST API where you define business rules, security, db operations, all that you cannot trust to a client.
- This API is used both from clients (using standard Backbone Ajax calls) and from server itself when the page is first requested (directly, using overridden
$.ajax
method).
- When a client requests a page, server creates all needed models and views, makes direct requests to API and renders HTML. Moreover, it remembers all data that came from API calls and which HTML elements correspond to which Views.
- Model/View code, HTML and Data is served to client. Here, HTML is fully rendered and functional, so even if the user turned off JavaScript, he can click links and browse the website (he will not get any dynamic features of course). But, if the Javascript is enabled, all Models and Views are recreated and re-binded to DOM nodes automatically in background, not making user wait.
- After that, the application works like a single-page app, requesting only data (json) from the same API, rendering templates on client.
This means that:
- You write presentation and dynamic code only once.
- First requested page is served and shown to user lightning fast, doesn't require to wait for all scripts to load and run, just HTML/CSS.
- Next pages are also very fast because only raw data is requested, templates are rendered on client. You can also make it visually attractive, not usual page reload. You can even play music while user browse the website.
- Search engines and Social Networks love you.
The architecture forces some sane requirements which will make you a better developer. Something like:
- Separate, well-defined API needed for server actions and business rules.
- No global variables.
- Views are treated more strictly than in general Backbone, more like stackable UI components.
- Clear separation between HTML rendering and dynamic behaviors.
A very simple example can be found in the source tree. I use Backbone as a basis for Models and Views, and Browserify deliver js package to client.
In my project I use inline templates with EJS as a templating engine. This has advantage of keeping HTML and code (I use CoffeeScript) in the same place. But the framework is capable of packaging templates from external files, with other templating engines like Jade. Please, see a templating example on how it could be done.
Please let me know if you are interested this approach, maybe it'd push me to start writing docs for it.