Modern web development approaches

Published Dec 31, 2017
Modern web development approaches

Few tips for stand out modern web development

In this article I will cover basic concepts, benefits as well as drawbacks of using single page JavaScript based frameworks.

First, what are single page applications?

Let’s see how traditional web applications work, Normally a full stack server side application generate all the data for web app on the server itself. Only then it is sent down to the client before the page could be rendered.

1_jHpMXjFqgpYOHKfat_HV0Q.png
Overview of Single Page Application (SPA)

Content is fetched from a database and then passed trough a controller and finally merge with view template before it is sent.

This manifests itself in the form of the page which reloads every time we navigate the application or website. JavaScript’s role here is very minimal. It is only responsible for controlling small parts of user interface.

Few years back, single page applications started to become popular among developers. A single page application makes a request to the server for a skeleton of HTML file, along with styles and scripts.

Meanwhile, subsequent requests are made to the server in the form of Ajax requests. The HTML page content itself is rendered using JavaScript and styled with CSS.

The advantage is we only fetch a subset of the content we require as opposed to the entire page, This provides less server load and faster user interface.

Below are the most popular JavaScript based single page application (SPA) frameworks:

Angular.js — Client library which attaches to static HTML with a set of it’s own attributes for data binding.

ReactJS — Component based client side library for building web applications.

Vue.js — Offers two-way data binding (can also seen in AngularJS) and server side rendering like in Angular 2 and ReactJS.

Ember.js — Client side library uses Handlebars template engine to build web applications.

Meteor.js — Full stack framework backed by NodeJS and MongoDB. Which uses Blaze, Angular and React for templating.

1_2_Se31naPtyCl2d1NF2aMQ.png

5 Best JavaScript Frameworks in 2017 — Hacker Noon

Single page applications create boundaries in between content, logic controllers and presentation. For MVC frameworks it acts as a separation of concerns.

Content — Usually is delivered in JSON and format using REST.

Logic controllers— Responsible for handling requests and send data back-forth to the application. Handled by using HTTP and WebSockets.

Presentation — Controlled by HTML templates which contain template tags to carry out such tasks like iterating over a data set.

A server side example

This example shows how we can fetch and render list of users of different levels.

Let’s start with server side controller which fetch users and return a list in JSON format.

/**
 *	Users controller (NodeJS)
 */
const app = express(),
  
/**
 *	This function fetches staff users
 *	from the MongoDB collection
 */
const fetchUsers = (offset = 0, limit = 10) => {
  return new Promise((resolve, reject) => {
    Users.find({}, {
      $offset: offset,
      $limit: limit
    }).then((result) => {
      if(error) {
        reject(error);
      }
      else {
        resolve(result);
      }
    });
  });
};

/**
 *	This function returns a list
 *	of users in JSON format.
 */
app.get('/staff/users', (request, response) => {
  fetchUsers()
  .then((result) => {
    response.status(200).json(result);
  })
  .catch((error) => {
    response.status(500).json(error);
  });	
});

If we request to the server to fetch some users from https://yourserver/staff/users the response will be following:

[
  {
    "name":"Savinda",
    "location":"Colombo"
  },
  {
    "name":"Thameera",
    "location":"Colombo"
  },
  {	"name":"Andy",
    "location":"California"
  },
  {	"name":"Ian",
    "location":"New York"
  }
]

Client-side controller

If we use client-side controller, the code will be something like this:

Template.users = {
  /**
   *	Array to store list of users.
   */
  users: [],

  /**
   *	This event  fires when a template is ready.
   */
  ready: () => {
    fetchUsers();
  },

  /**
   *	Make AJAX request to fetch list of users.
   */
  fetchUsers: () => {
    let request = new XMLHttpRequest(),
      url 	= 'https://yourserver/staff/users'

    /**
     *	We make the request...
     */
    request.open('GET', url, true);

    /**
     *	When the request has completed...
     */
    request.onload = () => {
      /**
       *	Check the response status code
          to make sure everything working fine...
       */
      if(request.status === 200) {
        /**
         *	Assign the response to the list of users.
         */
        this.users = JSON.parse(request.responseText);
      }
    };
  }
};

We can render a user from the list using following code:

<template name="user">
  <li>
    {{ name }} is in {{ location }}.
  </li>
</template>

View template of mvc app which render users looks like this:

<html>
  <head>
    <title>
      Single Page Application | Users
    </title>
  </head>
  <body>
    <ul class="list-of-users">
      {{ each users }}
        {{> user }}
      {{ end }}
    </ul>
  </body>
</html>

When the browser initially render the template, it calls controller for template to fetch users. When users are fetched, they are automatically rendered to a list.

Some important concepts

These are some concepts if you are beginner to client side JavaScript development.

Controllers — Responsible for managing the data and the attached view file. Also contains functionality to deal with UI behaviors of app.

Templates — HTML files that contain special tags in order to render the content.

Views — Similar to templates in usage and functionality. But view is an overall collection of different components that put together the whole page.

Binding — Process the render content of view which updates automatically when the data inside the controller for that view changes.

Routing — This uses HTML5 pushState to deep link the different views when navigating around the app.

Ajax requests — Send requests to server in order to fetch data without reload a page. There would be no single page applications if there’s no Ajax.

Web sockets — API that used to establish persistent connections between web browser and server. HTTP protocol requests data and then disconnects.

Discover and read more posts from Savinda Rukshan
get started