Skip to Content

Create A Single Page Application with JavaScript

In this tutorial, we'll discover how to create dynamic single-page applications that'll impress users and enhance their browsing experience. No more page reloads - just pure web magic! This tutorial is perfect for anyone, whether you're a beginner or a seasoned developer. Let's get started!

Ad - Web Hosting from SiteGround - Crafted for easy site management. Click to learn more.
Advertising Disclosure: I am compensated for purchases made through affiliate links. Click here for details.

What is a Single Page Application?

A single-page application (SPA) refers to a web application or site that engages with users by dynamically updating the current page with fresh data from the server, rather than the traditional approach of the browser loading entirely new pages.

The Code

HTML Code

We'll start by creating a basic HTML page in the root directory of our project named index.html with three links in the top navigation area and a container to hold the page content. We'll also create a reference to our script file where the magic happens:

<!DOCTYPE html>
<html lang="en">
<head>
<title>JavaScript SPA</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1" />
</head>
<body>
<header>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>

<main>
<div id="content">
<!-- Content will be loaded here dynamically -->
</div>
</main>

<script src="js/main.js"></script>
</body>
</html>

Now, we'll create three pages in a sub-directory of our root named page and add the following files:

home.html

<h1>Home Page</h1>
<p>This is the home page.</p>

about.html

<h1>About Page</h1>
<p>This is the about page.</p>

contact.html

<h1>Contact Page</h1>
<p>This is the contact page.</p>

JavaScript Code

Now, let's dive into the functionality! We'll create a custom function named Navigate() that accepts a single parameter page that is the link to our HTML file. We'll then use JavaScript's built-in fetch() method to load our HTML file dynamically and place the resulting contents in our content placeholder element:

function Navigate(page) {
let container = document.getElementById("content");

fetch("page/" + page + ".html")
.then(response => response.text())
.then(html => {
container.innerHTML = html;
})
.catch(error => {
console.error("Error fetching page: ", error);
}
);
}

Now that the function is created, we can pass in a default value so the homepage loads on page load:

Navigate("home");

Finally, we'll create an event listener for our navigation menu links so a new page loads anytime a link is clicked. The page name is determined by the anchor tag's href value and strips out the preceding symbol. Then we call our custom function to load the page:

document.querySelectorAll("nav a").forEach(link => {
link.addEventListener("click", function(event) {
event.preventDefault();

let page = this.getAttribute("href").substring(1);

Navigate(page);
});
});

Conclusion

That's it! You've learned how to create your first single-page application with JavaScript using only a few code snippets!

The full code example is available in the GitHub repository, so you can clone and make changes to fit your application.

You can take this a step further in the PHP single-page application tutorial where you can set a custom 404-page handler that changes the URL dynamically.

Posted by: Josh Rowe
Created: March 30, 2024

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.