← Learn Javascript

Single Page Applications

Using vanilla JS, jquery, Vue.js, or React

slides | md

Traditional websites

In a traditional approach to loading new content, users click on a hyperlink, leave the current page, and the browser loads an entirely new page (including all its resources).

true

Single Page Applications

A single-page application (SPA) is a web app or website that dynamically rewrites the DOM (the entire web page or just selected nodes) with new data from the server.

true

Benefits

  • You can keep track of state across multiple pages in your website. For example, variables with answers to a quiz that spans multiple pages.
  • Hosting a web app that runs in the client is easier (and cheaper) to host (you don't need a PHP server for app functions).
  • Your website is potentially faster because the browser doesn’t have to load and re-render a brand new page for each new "view" because data loads asynchronously in the background.
  • These seamless transitions also make a website feel more responsive to input, like a native app.

Considerations

The main cons with SPAs are related to the fact that they load data without changing the URL:

  • To let users link directly to internal pages, developers can rewrite the url in the browser.
  • If implemented correctly, the back button will also work.
  • Search engines can't see content if it doesn't exist on a page. Not so much an issue with "apps"
  • Site analytics have to be handled specific to the solution.

πŸ‘‰ Can you spot an SPA?

See if you can spot an SPA in the wild.

  1. Find an example website that might be an SPA.
  2. Does the content in the page...
    1. change very quickly?
    2. change, yet the browser doesn't show a loading bar or "refresh state"?
  3. See the next section for ways to test the site...

πŸ‘‰ Use DevTools to inspect an SPA

To test the example...

  1. Open the Network tab in Dev Tools and browse the site.
  2. Is content loading in the background through asynchronous XHR requests?
  3. See if you can identify "the stack" using the console or source code. Try using this tool: builtwith.com
Solution

Popular examples: Facebook, Twitter, Gmail, Netflix, Trello, Google Maps, Google Drive

Simple SPA - Update specific text

  • There are multiple ways to tap into the benefits of an SPA without using a fancy framework.
  • This simple SPA gets data for content in each page from a JS object:
var pages = {
    "home": {
        "title": "This is the home page",
        "content": "This is the content of the home page"
    },
    "about": {
        "title": "This is the about page",
        "content": "This is the content of the about page"
    },
    ...
};

Simple SPA Chart - Hide / reveal sections of a page

This "show-hide" version contains all the sections of a site (hidden by default) then JS reveals them as needed, hiding all others.

<!-- index.html -->
<section class="page1">
    <h1>Page 1</h1>
</section>
<section class="page2">
    <h1>Page 2</h1>
</section>
// main.js (simplified)
function displayView(next){
    prev.style.display = "none";
    next.style.display = "block";
}

Simple SPA Chart - Update sections of a page with external files

This simple SPA chart loads html pages for different "views"

<!-- contents of intro.html -->
<h1>Intro</h1>

...which are loaded dynamically into div#main of index.html. See the vanilla JS or jquery examples for more.

$("#main").load('views/intro.html');
Note: In order for Javascript to load remote content (most SPAs) it must be running on a web server using the http protocol, like http:// or https://. If your url begins with file:// then it won't work. See instructions on the next slide to run a server...

How to start a web server

To test the example...

  1. Install Node using the installer or Homebrew (Mac) or Scoop (Windows)
  2. Install serve package globally:
    npm install --global serve
  3. Change to your project directory cd <directory> and run serve to start the server.
  4. Or specify the folder you want to serve:
    serve <directory>

More examples

Other simple examples that manage state / change views:

Frameworks

Popular SPAs like Facebook and Google docs are complex to create and manage. Thus, companies have created several frameworks to make their own development more efficient. You can always find others trending, depending on what year it is.

  • Angular (developed/used by Google)
  • React (developed/used by Facebook, Instagram, and WhatsApp)
  • Vue.js (developed by ex-Google employees)

Each of these libraries have benefits and drawbacks. Angular and React are the most popular, but Vue is the easiest to learn.

Vue.js

  • Vue ("view") is a JS framework that uses a component-based programming model for building user interfaces.
  • Declarative Rendering Vue extends standard HTML with a template syntax {{ }} to describe output from your program.
  • Reactivity Vue automatically tracks and updates the DOM when your program state changes.

Open the Vue demo

<div id="app">
	<h1>{{ title }}</h1>
	<button @click="count++">
		Count is: {{ count }}
	</button>
</div>
<script type="module">
import { createApp } from 'vue'
// create and mount the app
createApp({
	data() {
		return {
			title: "Hello world!",
			count: 0
		}
	}
}).mount('#app')
</script>

Vue.js Components

  • The Vue.js component-based architecture means all content and functionality is stored inside external files, or components.
  • The application imports components as needed, making them easy to reuse (e.g. a footer across your website is always the same).
  • A typical architecture (for a todo application) might look like:
App (root component)
β”œβ”€ TodoList
β”‚  └─ TodoItem
β”‚     β”œβ”€ TodoDeleteButton
β”‚     └─ TodoEditButton
└─ TodoFooter
   β”œβ”€ TodoClearButton
   └─ TodoStatistics

Vue.js vs. jQuery

All JS apps need to change the DOM (to update/insert/remove elements and content)...

  • Vue.js updates the DOM automatically to reflect the state of variables in the app.
  • jQuery (and Vanilla Js) manipulate the DOM directly, leaving it up to the programmer to manage and keep the state of the application consistent with the DOM.

Don't use them together: If you manipulate the DOM with jQuery then Vue.js (or React) won’t be informed that something was changed externally, so can't manage state automatically.

Vue.js vs. jQuery

Action Vue.js jQuery or Vanilla JS
Selection of elements Automatic $(selector) (required)
Change the DOM Automatic "Reactive" $(selector).html() required
Component architecture Built-in (default) Custom code required
Text Interpolation {{ }} template syntax "string " + value required
Update attributes :id attribute binding $(selector).css({...})

Reference: jQuery vs Vue.js

Ways to use Vue.js

Vue.js is flexible in how you implement it within a project. These are listed from simple to advanced concepts.

  1. Single page: Mixing static content with Vue.js can be done easily.
  2. Single-File Components (SFC) encapsulate the template (HTML), logic (JS), and styling (CSS) of a Vue component in a single file.
    • Pros: Co-location and coupling of concerns, component-scoped CSS
    • Cons: SFCs require a build step
  3. Server-Side Rendering (SSR) where Vue.js can be used with Node to create strings on the server.
  4. Static Site Generation (SSG) like SSR but can be served as static pages.

React

  • React is a JavaScript library for building user interfaces and single-page applications.
  • React uses JSX (JavaScript XML), a syntax extension to JavaScript that makes it easier to write and add HTML in React.
  • JSX elements are the same as JavaScript expressions. They can be saved in a variable, passed to a function, stored in an object or array.
// JSX element being saved in a variable...
const navBar = <nav>I am a nav bar</nav>;
// ... or an object
const colors = {
	red: <h1>A sunset</h1>
	green: <h1>Some grass</h1>
	blue: <h1>The sky</h1>
}

JSX Syntax

  • Wrap multi-line JSX expression in parentheses.
  • JSX expressions must have exactly one outermost element, even if its a simple <div></div>
const myDiv = (
  <div>
    <h1>Hello world</h1>
  </div>
);

Rendering JSX

In React, for every DOM object, there is a corresponding virtual DOM object (see ReactDOM in the code example). A virtual DOM object is a representation of a DOM object, like a lightweight copy.

// import libraries
import React from 'react';
import ReactDOM from 'react-dom';
// render to #app
ReactDOM.render(<h1>Hello world</h1>, document.getElementById('app'));
Reference: Introducing JSX

Rendering JSX with a component

This code example is the same as the previous example, but the JSX is stored in a reusable component:

// import libraries
import React from 'react';
import ReactDOM from 'react-dom/client';
// JSX is stored in a reusable component
function HelloComponent(props) {
  return <h1>Hello World!</h1>;
}
// render to #app
const app = ReactDOM.createRoot(document.getElementById("app"));
app.render(<HelloComponent />);

React Components

  • A React components are pieces of reusable UI (user interface) that contain their own markup, appearance, and logic.
  • A component can be as small as a button, or as large as an entire page.
  • Traditional website development separates code by technology (HTML, CSS, JS in separate files). React separates code by concernβ€”so a component will contain Javascript, HTML (JSX), and CSS inside a single file.

React & CSS

Because React components are "drag and drop" they must contain all the information about appearance. There are several different ways to write CSS in React including external stylesheets, inline styles <div className="main" style={{color:"red"}}>, and (what appears to be the most common) using styles inside objects:

// example component
import { React } from "react";
function App() {
  const styles = {
    main: {
      backgroundColor: "#f1f1f1",
    },
    inputText: {
      color: "red",
    },
  };
  return (
    <div className="main" style={styles.main}>
      <input type="text" style={styles.inputText}></input>
    </div>
  );
}
export default App;

React adds complexity

These examples are intended to show the basics, keep in mind that to use React in production:

You can set this all up manually, or use something like react-react-app to generate the project structure.

React and Express

Using React with Express (ES5) requires Babel...

Next steps

  1. Complete the Vue.js tutorial
  2. Complete the new React tutorial
  3. Start working on homework listed in the schedule.

References

Presentation comments ...