Single page architecture is an approach used for building web apps that have smooth inter-page-transitions. The transitions are so smooth and fast that they look like native apps. The basic principle of an SPA is that all of the code is in one document (one HTML file).
Why single page architecture?
- Single page applications give your website/web apps a more dynamic and fluid feel
- It opens doors for some clever design choices
- Most of the pages data is loaded on the first time. So, transition between pages won’t require any server call
- Since most of the things are loaded at once, the transition between pages will work offline also
- All the html code is housed in one HTML file (Although modern frameworks allow code seperation using multiple html and js files, All the code is finally rendered in one html file as a bundle or on-demand ajax calls)
- The code for different pages should be put into different div tags
- Only one of these divs should be visible at a time
- All the API calls(if any) should be made through Ajax on the client side itself.
Let’s make a simple website with SPA
- Create an empty project directory
- Inside the directory, create an index.html file with basic HTML tags like Head, Title, Body etc.
- Create two folders “js”, and “css” where the js and css files will be placed
- Put three div tags inside the body tag, which will represent three pages
- Keep the div ids as “page-1”, “page-2” and “page-3” respectively
- Put some sample contents into the three divs
- Create a file called app.js inside the js folder. And include it as a script in index.html.
- Inside app.js, create 3 funciton for showing the three pages respectively. Set style.display as “none”
to the div that you want to hide. Your app.js file should look something like this
- Now, we want page-1 to be show at the begining. So, we should call the showshowPage1() function inside a script tag in index.html.
<script> showPage1(); </script>
- Now, if you open the index.html page on the browser, it will look like this.
- Now we need to navigate from one page to another. So, we will add two buttons in each page/div to navigate to the other two pages
- Call the function in app.js through the onclick attribute of each of the buttons.
- If you open the index.html in the browser now, you will see a very small example of a SPA website
- Click the button to navigate from one page to another. And notice that the URL is the same as all the code is in index.html
So, this was just a small representation of an SPA based website. With the same steps, you can build a much bigger website. It’s just a matter of what content you are putting inside the divs. But do keep in mind that the common elements like navigation bar should be kept outside the divs as it should appear in all the pages.
How this post helped you in some or the other way. Have fun making SPAs. And if you run into any problem while following the steps, reach out in the comments below.