Single Page Application: Advantages and Disadvantages

Single Page Application: advantages and disadvantages

Let's look at one of the most popular SPA sites, GMail.

1. SPA is extremely good for very responsive sites:

Server-side rendering is not as hard as it used to be with simple techniques like keeping a #hash in the URL, or more recently HTML5 pushState. With this approach the exact state of the web app is embedded in the page URL. As in GMail every time you open a mail a special hash tag is added to the URL. If copied and pasted to other browser window can open the exact same mail (provided they can authenticate). This approach maps directly to a more traditional query string, the difference is merely in the execution. With HTML5 pushState() you can eliminate the #hash and use completely classic URLs which can resolve on the server on the first request and then load via ajax on subsequent requests.

2. With SPA we don't need to use extra queries to the server to download pages.

The number of pages user downloads during visit to my web site?? really how many mails some reads when he/she opens his/her mail account. I read >50 at one go. now the structure of the mails is almost the same. if you will use a server side rendering scheme the server would then render it on every request(typical case).
- security concern - you should/ should not keep separate pages for the admins/login that entirely depends upon the structure of you site take paytm.com for example also making a web site SPA does not mean that you open all the endpoints for all the users I mean I use forms auth with my spa web site.
- in the probably most used SPA framework Angular JS the dev can load the entire html temple from the web site so that can be done depending on the users authentication level. pre loading html for all the auth types isn't SPA.

3. May be any other advantages? Don't hear about any else..

  • these days you can safely assume the client will have javascript enabled browsers.
  • only one entry point of the site. As I mentioned earlier maintenance of state is possible you can have any number of entry points as you want but you should have one for sure.
  • even in an SPA user only see to what he has proper rights. you don't have to inject every thing at once. loading diff html templates and javascript async is also a valid part of SPA.

Advantages that I can think of are:

  1. rendering html obviously takes some resources now every user visiting you site is doing this. also not only rendering major logics are now done client side instead of server side.
  2. date time issues - I just give the client UTC time is a pre set format and don't even care about the time zones I let javascript handle it. this is great advantage to where I had to guess time zones based on location derived from users IP.
  3. to me state is more nicely maintained in an SPA because once you have set a variable you know it will be there. this gives a feel of developing an app rather than a web page. this helps a lot typically in making sites like foodpanda, flipkart, amazon. because if you are not using client side state you are using expensive sessions.
  4. websites surely are extremely responsive - I'll take an extreme example for this try making a calculator in a non SPA website(I know its weird).

Updates from Comments

It doesn't seem like anyone mentioned about sockets and long-polling.
If you log out from another client say mobile app, then your browser
should also log out. If you don't use SPA, you have to re-create the
socket connection every time there is a redirect. This should also
work with any updates in data like notifications, profile update etc

An alternate perspective: Aside from your website, will your project
involve a native mobile app? If yes, you are most likely going to be
feeding raw data to that native app from a server (ie JSON) and doing
client-side processing to render it, correct? So with this assertion,
you're ALREADY doing a client-side rendering model. Now the question
becomes, why shouldn't you use the same model for the website-version
of your project? Kind of a no-brainer. Then the question becomes
whether you want to render server-side pages only for SEO benefits and
convenience of shareable/bookmarkable URLs

Difference between Single Page Application and Web Application.

See this answer. An overly simplified comparison, in terms of development effort, is

Multi page application:

  1. User action embodied in HTTP request (e.g. HTTP POST, HTTP GET)
  2. Request is handled, server responds with HTTP page

Drawbacks: requires many pages just to respond to every user action (e.g. add item to list, update form data), whereas in a SPA data binding can do much of the work of updating the view for you. Secondly, it's the responsibility of the web application to maintain state which is otherwise lost between full page requests. In contrast, the SPA can maintain its state in memory, between XHRs without additional work while the browser stays on the same page.

Single page application (SPA):

  1. configure routing on both client and server side
  2. code "controllers" on both client and server
  3. initialize the framework on client
  4. Handle user actions in JavaScript
  5. Handle XHR request/response

These are just typical steps I've noticed in developing both single- and multi-page apps, and this doesn't necessarily or extensively represent all cases.

To develop SPAs, frameworks such as AngularJS are highly encouraged and highly opinionated, an advantage of which is guidance on structuring your client-side JavaScript.

Where multi page applications respond to user actions with full page loads, single page applications by definition are limited to 1 page (otherwise they'd be multi page) and instead rely on XHR.

Why do we need a Single Page Application?


I believe that this is the direction most websites should be moving in considering the number of devices that users utilize today, and the abilities and limitations of each.


IMPORTANT:

Before reading the rest of this, please understand that this concept is built on the foundation of basic principles of designing for the web. In order to design a single page application for all devices and situations, it cannot be run exclusively as a single page application. You must build a foundation that will work on the most basic of browsers with highly limited features and enhancing the user's experience according to their device's capabilities.

This may cause more work for you, but you will be capable of satisfying a larger and more diverse audience, which is much more impressive than throwing together a web app built only for modern desktop or phone browsers specifically.



Decrease load time and/or weight

Single page applications are more capable of decreasing load time of pages and the amount of data transfer from server to client.

Some of the most heavily impacting features of this method include :

  • storing any global functionality once it is loaded the first time,
  • allowing easier data transfer between pages and a more complex user interface
  • removing the cost of loading a whole page after a postback when you only need specific components

Increased chance of over complicating

This design method may allow for laziness in the developer and more interference from an end user. As a developer, be sure that your UI does it's job (get, display and submit to server) and that the server does it's job (provide, validate and submit to database). Most end users won't attempt to break your system using the information in a javascript file, but including information about your data structure is asking for trouble in my opinion.

Start with a strong architecture!

As with any webpage, the processing of data can be moved directly into service handlers instead of pages which could result in an architecture utilizing the following layers:

  • Database (Data Storage)
  • BL (Data Handling and Transport)
  • User Interface (Data Display and User Interaction)

Services over page handling

In my opinion using services is pretty much a requirement for organized and modulated code in a website. The standard get and post methods used in backwards compatible website can also use these services to hit services representing business objects instead of pages. This allows your code to be more generalized across modules concerning the same objects.

The update to a single page application then becomes simplistic in that you can initialize any UI to pick up the get or post methods and perform them using AJAX methods instead of causing a postback for events, thus a single page instance.

A side effect of using these services to handle UI events is that you eliminate the need for event handling in a code behind file except for life cycle events. The life cycle events are useful for handling and modifying relevant data to display based on the situation as well as modifying the returned html to lighten the load on the user's device.

Deferred Loading!

Any complex website will come with complex modules and plenty of unique components.

A benefit you gain from using a single page application is that you have the option to deffer the load time to an ajax process and do so whenever you like for any part of your application (i.e. first attempt to use a module, dead time after initial page load, etc), making the initial load faster and the processing time more controlled.

My list of best practices

As for best practices.. there are quite a few optimizations that could and should be made to a design intending to use this method, such as :

  • storing information as it comes, obliterating when no longer relevant
  • loading in script, html and js files through ajax only when needed
  • using data loaded on one page in another if it can be instead of reloading for each new "page"
  • minimalist data structure for the UI since it is a means for displaying and not for processing.
  • don't obsess with validation on the UI because your services should already be built to validate any information submitted to it

These optimizations are helpful with load time, data handling and object associations. Obviously this is not a complete list, but it is a great head start to building you single page application.

Finally, I would suggest researching concepts for designing for one web to help build a solid foundation. After that, the rest is relatively simple enhancements. (TIP: One of those enhancements is to catch all actions resulting in a postback and use the information to build a asynchronous call instead).

There is all sorts of information on this, and all sorts of libraries to use, but I would suggest using your own code as much as possible for the basic functionality and to get into the library code that solves your issues and do some research instead of trying to implement a complex system with generic library code. Using their code as an example may lead to a smaller overhead and stronger code for your specific situation.

Good Luck!

back-end vs front-end controlled web application

  1. I researched again on csrf and IIUC, XHRs are better against csrf since:

    • modern browsers automatically add origin headers to all XHRs, which blocks all requests from unexpected domains (together with allow-origin config on server-side).
    • And we can do even more by manually adding csrf tokens to js code when rendering pages on server-side (to be sent with requests in XHRs later). The tokens inside js code are impossible for the attacker to acquire. EDIT: this is not unique for single-page apps, I've learned that traditional server-rendered sites can do the same by writing the token in a hidden field in a form after reading the Synchronizer token pattern chapter of wikipedia. Rather than <input type="hidden" name="csrftoken" value="..." />, I thought of <script>var csrfToken={{server.token()}}</script> ({{}} is the server side template). The former is used when the form is posted, mine is used when js code sends XHRs. My idea is a mix of the Synchronizer token pattern chapter and its next in the wikipedia page. By these means, if our site is XSS free, the attacker won't be able to get the token in the session/page/js, and the request he tricks the user's browser to send will fail without the token.

      Which leads to: modern single-page apps are XHR heavier than traditional web apps, which utilizes full-page server-side render with js-manipulated view changes (with XHRs) on different occasions. And thus, more secure.

  2. 1 request is definitely better than 5, if only for request counts' sake. Here we make the trade-off: By adding a few traffic to loading the page, we gain:

    • As OP addressed, server interfaces reusable by mobile apps since they return pure data rather than htmls which mix data with webpages.
    • Better separation of concerns for both front and back ends. Backend developer writes smaller single-functionality interfaces. And even better for frontend developer: views, styles, interaction logic scripts (as we can see in .vue files) are all organized in components, fewer things to worry about, happier we can be.

      Therefore I think the trade is totally worth it.



Related Topics



Leave a reply



Submit