Basic Vanilla Javascript Single Page App Set-Up

Sam Evans
2 min readDec 4, 2020

In this post, I will run through a simple initial set up for a single page web application written in vanilla javascript.

What is a single page app (spa)?

A single-page application (SPA) is a web application or website that interacts with the web browser by dynamically rewriting the current web page with new data from the web server, instead of the default method of the browser loading entire new pages. The goal is faster transitions that make the website feel more like a native app.

Set Up

The simple basis for our SPA is setting up an event listener for a ‘load’ and for a ‘hashchange’. The ‘load’ event fires when your script is loaded by your index.html file, and the ‘hashchange’ event is fired when the trailing section of the url changes.

We then define a function routeChange that is called when either of those events fire. routeChange will parse the current hash in the url bar, then pass that to a dictionary lookup to load the appropriate view. If that path doesn’t exist, load either the home page, or an error page.

The page view functions can do whatever you want: clear out the body of the DOM, and load a whole different view, load a modal over the current view, or anything else!

See the below simple example.

--

--