Before any new project I like to take a moment to think about which frameworks will work best with what I am trying to build, despite my subjective opinions about each option. Lately I fell in love with AngularJs and NodeJs, but unfortunately I can’t use them in every project.
- The platform can contain simple pages like any PHP application.
- It should load some pages or process forms through Ajax, but not necessarily all of them. It should be the developers choice which is loaded through ajax and which is not.
- Should have a simple way to switch between loading a page via Ajax or through a full page request.
- Should allow the developer to specify where should the loaded section render in the page.
Basically the framework should be something that can help turn a normal web application into a single page one in a manner of minutes.
I started developing something that fits into this description using Backbone, jQuery and RequireJs.
I’ve used Backbone Views to define specific, self contained functionality for a section and to organise your code better into blocks of functionality.
Everything that you want to load without a page refresh is just prepended with a #! in front of the url. The forms are processed in a similar way as well. There is also a way to make the content load in a specific element when you click a link or submit a form. I am still working on what the simplest approach to this is, so if you have any suggestions let me know.
To spare the user the trouble of setting up each view object, these are created automatically for you if you specify something like data-handler=”app/path/to/view” on the DOM element. This automatically loads the view using RequireJs, creates an instance of it and initiates each section that needs that handler. This way you deal more with the functionality instead of configurations and setting up your architecture.
In order to convert an application to a single page application with this tool you would have to simply follow these steps:
- Define where the main content should load and configure that in the framework
- Add #! in front of all links that you want to convert
- Define custom views for areas with special behaviour and add the path to the view in the data-handler attribute for these areas
- Modify your application to return the pages with only the main content without any layout, menus or other sections.