0% found this document useful (0 votes)
101 views36 pages

SPA Design for Developers

Single Page Application (SPA) designs involve moving the presentation layer to the client-side so that the entire application runs within a single web page. In an SPA, views are dynamically generated on the client rather than retrieved from the server as full pages. This allows navigation within the application without full page refreshes, providing a more desktop-like user experience. The initial page load retrieves all necessary code for generating views, and subsequent interactions involve only retrieving additional data from the server via APIs.

Uploaded by

Helly Mavani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views36 pages

SPA Design for Developers

Single Page Application (SPA) designs involve moving the presentation layer to the client-side so that the entire application runs within a single web page. In an SPA, views are dynamically generated on the client rather than retrieved from the server as full pages. This allows navigation within the application without full page refreshes, providing a more desktop-like user experience. The initial page load retrieves all necessary code for generating views, and subsequent interactions involve only retrieving additional data from the server via APIs.

Uploaded by

Helly Mavani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Single Page Application (SPA)

Front-end Design
SPA
• In an SPA, the entire application runs as a single web page.
• In this approach, the presentation layer for the entire application has been
factored out of the server and is managed from within the browser.
• To get a better idea of what this looks like, you’ll review a couple of illustrations.
large web application that uses a traditional server-side
design.

With this design, each request for a new view (HTML page) results
in a round-trip to the server. When fresh data is needed on the
client side, the request is sent to the server side. On the server side,
the request is intercepted by a controller object inside the
presentation layer. The controller then interacts with the model
layer via the service layer, which determines the components
required to complete the model layer’s task. After the data is
fetched, either by a data access object (DAO) or by a service agent,
any necessary changes to the data are then made by the business
logic in the business layer.
Control is passed back to the presentation layer, where the
appropriate view is chosen. Presentation logic dictates how the
freshly obtained data is represented in the selected view. Often the
resulting view starts off as a source file with placeholders, where
data is to be inserted (and possibly other rendering instructions).
This file acts as a kind of template for how the view gets stamped
whenever the controller routes a request to it.
After the data and view are merged, the view is returned to the
browser. The browser then receives the new HTML page and, via a
UI refresh, the user sees the new view containing the requested
data.
SPA, the presentation layer moves to the client-side code,
and transactions never require a browser refresh.

Moving the process for creating and managing views


into the UI decouples it from the server. From an
architectural standpoint, this gives the SPA an
interesting advantage. Unless you’re doing partial
rendering on the server, the server is no longer required
to be involved in how the data is presented.
The overall SPA design is nearly the same as the
traditional design. The key changes are as follows: no
full browser refreshes, the presentation logic
resides in the client, and server transactions can be
data-only, depending on your preference for data
rendering.
No browser refreshes
• In an SPA, views aren’t complete HTML pages.
• They’re merely portions of the DOM that make up the viewable areas of the
screen.
• After the initial page load, all the tools required for creating and displaying
views are downloaded and ready to use.
• If a new view is needed, it’s generated locally in the browser and dynamically
attached to the DOM via JavaScript.
• No browser refreshes are ever needed.
Presentation logic in the client
• Because our presentation logic is mostly client side in an SPA, the task of
combining HTML and data is moved from the server to the browser. As on the
server side, source HTML contains placeholders where data is to be inserted
(and possibly other rendering instructions). This client-side template is used as
a basis for stamping out new views in the client. It’s not template HTML for a
complete page, though. It’s for only the portion of the page the view
represents.

• The heavy lifting of routing to the correct view, combining data with the HTML
template, and managing a view’s lifecycle is typically delegated to a third-party
Java-Script file commonly referred to as an MV* framework (sometimes called
an SPA framework).
Server transactions
• In an SPA, several approaches can be used to render data from the server. These
include server-side partial rendering, in which snippets of HTML are combined
with data in the server’s response.
• The data-exchange format is typically JavaScript Object Notation (JSON),
though it doesn’t have to be. Even using client-side rendering, though, the
server still plays a vital role in the SPA.

• Even if you’re already using a server-side design pattern such as Model-View-


Controller (MVC) to separate views, data, and logic, reconfiguring your MVC
framework for use with SPAs is relatively easy.
• Therefore, frameworks such as ASP.NET MVC or Spring MVC can still be used
with an SPA.
An SPA starts with a shell
• The single-page part of the SPA refers to the initial HTML file, or shell. This
single HTML file is loaded once and only once, and it serves as the starting point
for the rest of the application. This is the only full browser load that happens in
an SPA. Subsequent portions of the application are loaded dynamically and
independently of the shell, without a full-page reload, giving the user the
perception that the page has changed.
• Typically, the shell is minimal in structure and often contains a single, empty
DIV tag that will house the rest of the application’s content. You can think of this
shell HTML file as the mother ship and the initial container DIV as the docking
bay.
• The code for the shell has some of the basic starting elements of a traditional
web page, such as a HEAD and BODY. The following listing illustrates a basic
shell file.
• The initial container DIV can have child containers beneath it if the
application’s viewable area is divided into subsections. The child containers are
often referred to as regions, because they’re used to visually divide the screen
into logical zones.

• Regions help you divide the viewable area into manageable chunks of content.
The region container DIV is where you tell the MV* framework to insert
dynamic content.
From traditional pages to views
• The “pages” of the application aren’t pages at all, at least not in the traditional
sense. As the user navigates, the parts of the screen that appear to be pages
are actually independent sections of the application’s content, called views.
The view is a portion of the application that the end user sees and interacts
with.
• Imagining the difference between the average web page and the view of an SPA
can be difficult. To help you visualize the difference, take a look at the following
figures. It shows a simple website composed of two web pages. As you can see,
both web pages of the traditional site contain the complete HTML structure,
including the HEAD and BODY tags.
• This shows the same website as an SPA. The SPA “pages” are only HTML
fragments. If the content of the viewable area of the screen changes, that’s the
equivalent of changing pages in a traditional website.

• When the application starts, the MV* framework inserts view 1. When the user
navigates to what appears to be a new page, the framework is swapping view 1
for view 2
The birth of a view
• If sections (or views) of the application aren’t part of the initial shell, how do
they become part of the application? As mentioned previously, the various
sections of the SPA are presented on demand, usually as a result of user
navigation. The skeletal HTML structure of each section, called
a template, contains placeholders for data. JavaScript-based libraries and
frameworks, commonly referred to as MV*, are used to marry data and at least
one template. This marriage ultimately results in the final view. All the screen’s
content beyond the shell gets placed into separate views.
• The completed view is attached to the DOM, as needed, either directly under
the initial container DIV, as illustrated in figure, or in one of the regions if there
are any.
View swapping for zero reload navigation
• All of this happens without having to
refresh the shell. So instead of getting
served a new static page for every
navigation request, the SPA can display
new content without a disruption for
the user. For a particular part of the
screen, content of one view is merely
replaced by the content of another
view. This gives the illusion that the
page itself is changing as the user
navigates.
• Navigation without a reload is a key
feature of the single-page application
that gives it the feel of a native
application. The interesting thing about
navigation in an SPA is that, to the user,
it looks like the page is changing. The
URL will look different, and even the
Back button can be used to take the
user to the previous “page.”
Benefits of SPAs over traditional web applications
• Renders like a desktop application, but runs in a browser —The SPA has the ability
to redraw portions of the screen dynamically, and the user sees the update instantly.
Because the SPA downloads the web-page structure in advance, there’s no need for
the disruptive request to get a new page from the server. This is similar to the
experience a user would get from a native desktop application; therefore, it “feels”
more natural. An advantage over even the desktop application, the SPA runs in the
browser, making its native-like, browser-based environment the best of both worlds.
• Decoupled presentation layer —As mentioned previously, the code that governs
how the UI appears and how it behaves is kept on the client side instead of the
server. This leaves both server and client as decoupled as possible. The benefit here
is that each can be maintained and updated separately.
• Faster, lightweight transaction payloads —Transactions with the server are lighter
and faster, because after initial delivery, only data is sent and received from the
server. Traditional applications have the overhead of having to respond with the next
page’s content. Because the entire page is re-rendered, the content returned in
traditional applications also includes HTML markup. Asynchronous, data-only
transactions make the operational aspect of this architecture extremely fast.
Benefits of SPAs over traditional web applications
• Less user wait time —In today’s web-centric world, the less time a user has to wait for the
page to load, the more likely the person is to stay on the site and return in the future.
Because the SPA loads with a shell and a small number of supporting files and then builds as
the user navigates, application startup is perceived as being quick. As the previous points
state, screens render quickly and smoothly, and transactions are lightweight and fast.
These characteristics all lead to less user wait time. Performance isn’t just a nice-to-have. It
equates to real dollars when online commerce is involved. A study by Walmart that was
published in Web Performance Today[1] indicated that for every 100 ms of performance
improvement, incremental revenue grew by up to 1%. In Walmart terms, that’s huge.

• Easier code maintenance —Software developers are always looking for better ways to
develop and maintain their code base. Traditionally, web applications are a bit of a Wild
West kind of environment, where HTML, JavaScript, and CSS can be intertwined into a
maintenance nightmare. Add in the ability to combine server-side code with the HTML
source (think Active Server Pages or JavaServer Pages scriptlets) and you’ve got a giant,
steaming pile of goo. JavaScript code is kept where it needs to be—out of the HTML and in
distinct units. With the help of third-party libraries and frameworks (for example,
Knockout, Backbone.js, and AngularJS), the HTML structure for an area of the screen and
its data can be maintained separately. The amount of coupling between the client and the
server is dramatically reduced as well.
Sample directory structure (by feature)

Sample directory structure (by functionality)

Simplified “by feature” directory structure


Routing and Navigation in SPA
What is a client-side router?
• Client-side routing is also about transitioning between different states in the
application.
• This could include modifications to the current view without navigation or other
activities that don’t include changes in the UI at all.
Traditional navigation
• In a traditional web application, navigation is thought of in terms of complete
web pages.
• When you enter a new URL into the location bar of a browser, usually a request
is sent for the page from the browser to a server, which responds by sending
you back an entire HTML page

In traditional web-page navigation, complete pages are sent back to the browser, triggering a refresh to display the new content.
• What’s actually sent back is the HTML document for the requested page.
• After the HTML for that page is received, the browser then fetches any other
source files referenced by the document, such as any CSS and JavaScript
include files.
• Other assets referenced in the HTML, such as images, also get downloaded
as the browser parses the document’s HTML and encounters their tags.
• To display the new content, the browser performs a complete refresh.
SPA navigation
• As you already learned, an SPA’s DOM typically starts off as a shell in the SPA’s
index page. That’s all that’s needed.
• The SPA’s modules and MV* framework, including supporting libraries, are
either downloaded with the index page or asynchronously loaded if an AMD
script-loading library is used.
• An SPA also has the ability to asynchronously fetch data and any remote
templates (partials) and other resources not already included and to
dynamically render views as needed.
• As the user navigates, views are seamlessly displayed.
• This, combined with the asynchronous fetching of data, gives the application a
smooth, native-like feel that makes for a great user experience.
• No more of the jarring interruptions that you usually experience when a page is
wiped clean and a new page is downloaded and displayed.
• The SPA does all of this without refreshing the initial page after it’s loaded.
• After the SPA is loaded, however, users need a way to access additional content within
the application.
• Because an SPA is still a web-based application, your users will expect to be able to use
the address bar and the browser’s navigation buttons for navigation.
• But how can navigation in an SPA occur with just one page and no browser refreshes?
• As it turns out, it’s not only possible, it’s easy.
• The JavaScript component that makes navigation in this single-page environment
possible is called a client-side router (or just a router).
• But remember that when we talk about navigation, we are talking about managing the
state of the SPA’s views, data, and business transactions as the user navigates.
• The router manages the application’s state by assuming control of the browser’s
navigation, allowing developers to directly map changes in the URL to client-side
functionality
• Using this approach, no server round-trips are needed.
• The router determines when a change in state is needed through
various methods of detecting changes in the browser’s location, such
as listening for particular events.
• Anytime a URL change occurs, the router tries to match part of the
new URL with an entry in its configuration.
overview of the navigation process in an SPA
Routes and their configuration
• Each entry in the router’s configuration is called a route.
• Routes are stored in the router’s configuration at development time, with each route
representing a logical flow within your SPA.
• You’ll typically design your routes as you design the layout for your application.
• Though router configuration varies from router to router, here are some typical
configuration terms:
• Name —With some routers, a name is given to the route. In others, the path serves as the
route’s identifier.
• Verb —Routes are sometimes defined with function names that match HTTP verbs—for
example, get() or put()—but not always. Some routers use more-generic names such as on() or
when() or route().
• Path —The path is a part of the URL. The path used to configure the router establishes a link
between a URL and a route/route handler. This allows the router to figure out which set of
actions to perform. Anytime the URL in the browser changes, the router compares the new URL
with all route paths in the configuration file’s path list for a match. When one is found, the route
is carried out. The path of the route must be a valid part of a URL. Although it’s quite common
that the path is simple text, some routers allow the use of regular expressions.
• Functionality —This is the associated code that may be executed, such as a controller or a
callback function. For the route to do anything, you need some associated code to run.
How do client-side routers work?
• Part of a client-side router’s job is to allow users to use the address bar and the
browser’s navigation buttons as they normally would in a traditional web application.
• At a minimum, many client-side routers offer the following features that make this
possible:
• Match patterns in the URL with paths defined by the route
• Allow for the execution of code in your application when a match is found
• Allow a view to be specified that will be displayed when the route is triggered
• Allow for parameters to be passed via the route’s path
• Allow users to use standard navigation methods of the browser to navigate the SPA
• Routers use one of two methods: either via the URL’s fragment identifier or
the HTML5 History API.
• Both methods enable the router to provide server-less navigation but in slightly
different ways. Because the HTML5 History API is newer and not supported by older
browsers, you’ll start your foray into the world of client-side routing with the more
traditional fragment identifier method.
The fragment identifier method
• The traditional method for routers to provide navigation in an SPA is via
a fragment identifier.
• The fragment identifier is any arbitrary string of text at the end of the URL and is
prefixed with a hash symbol (#). This optional part of the URL references a
section of the current document, not a new document.

Browsers treat this part differently from the rest of the URL. When a new fragment identifier is added to the URL,
the browser doesn’t attempt to interact with the server. The addition does, however, become a new entry in the
browser’s history.
• This is important because all entries in the browser’s history, even those
generated from the fragment identifier, can be navigated to via normal means,
such as the address bar and the navigation buttons. To see this in action, go to
any website, such as www.manning.com. Next, try executing the following in
your browser’s console:

• window.location.hash = "hello";

• As you’ll see, doing this results in hello being added as the URL’s fragment
identifier. The URL should look like this after the line executes:

• http://www.manning.com/#hello

• This action also adds a new entry in the browser’s history. Now you can
navigate back and forth between the fragment identifier and the original URL.
Exploiting the browser’s location object
• The location object contains an API that allows you to access the browser’s URL
information.
• In an SPA, routers take advantage of the location object to programmatically
gain access to the current URL, including the fragment identifier.
• The router does this to listen for changes in the fragment identifier portion of
the URL, via the window’s onhashchange event (if available in that browser
version—otherwise, it polls for hash changes).
• When a change occurs, the pattern in the new hash string is compared to all the
paths in each route from the router’s configuration. If a match exists, the router
executes any process specified and then displays the view from the matching
route.
• For example, imagine you have a link to your fictitious department’s main contact page
in your website header. The link’s code points to a fragment identifier URL:
• <a href="#routes/contact">Contact Us</a>
• When you click this link, the browser’s fragment identifier changes from its initial value
to #/routes/contact.
• Because the router actively listens for changes in the fragment identifier, this new hash
is detected. Upon detection, the router searches all routes in its configuration for a path
matching /routes/contact. When it finds a match, the route in the following listing is
carried out.
Faculty list route

Default route
Summary - Routers
• Routers are libraries/frameworks that allow you to specify a desired state for
your application for a given URL.
• Routes are configured in a router’s configuration.
• Routing in an SPA occurs in the browser. No server requests are required.
• Routers use one of two methods to achieve client-side routing: the fragment
identifier or the HTML5 History API.
• The HTML5 History API method for routing normally requires you to explicitly
state in the router configuration that you want to use it. It also requires a few
code changes, including changes on the server.
• The same route can be used to display different outcomes by incorporating
route parameters in a route’s path. Route parameters are variables defined in
the path of the route that allow information to be passed via a URL.

You might also like