When you move from one page to another on a website, some of the content disappears briefly before being replaced by the contents of the new page. But other elements seem not to be affected at all. For example when navigating this website (Stack Overflow), across pages, the top bar div doesn’t flinch.
How can this effect be achieved? Preferably with vanilla HTML, CSS and JS. Can it be done without combining all the pages into one file?
How did Stack Overflow do it with their top bar?
2
Answers
From what I've gathered so far:
The top bar of Stack Overflow only seems unaffected without throttling.
If you really want to, consider make your web app an SPA (Single Page Application). But this could be more effort than it's worth, just for the sake of aesthetic.
A Single Page Application (SPA) is a web application or website that interacts with the user by dynamically rewriting the current page, rather than loading entire new pages from the server. SPAs use JavaScript to update the content of the page dynamically, providing a smoother and more responsive user experience.
In a traditional multi-page application, when you navigate to a different page, the browser sends a request to the server, which responds by sending a completely new HTML page. In contrast, SPAs load the initial HTML, CSS, and JavaScript resources, and subsequent interactions with the application are handled by JavaScript, typically using AJAX (Asynchronous JavaScript and XML) or other techniques to fetch and update data without requiring a full page reload.
Here’s a simple example of how you might create a basic SPA using vanilla JavaScript:
HTML Structure:
Create a basic HTML file with a container element where the content will be dynamically updated. For example:
JavaScript (app.js):
Write JavaScript code to handle the dynamic loading of content. For simplicity, you can create separate HTML files for different pages and load them dynamically. Here’s a basic example:
In this example, when a navigation link is clicked, the
loadPage
function is called with the page name, and it fetches and injects the corresponding HTML content into the designated container.HTML Files for Each Page:
Create separate HTML files for each page (e.g., home.html, about.html, contact.html), containing the specific content for that page.
This is a very basic example, and in a real-world scenario, you might want to consider using a front-end framework or library (such as React, Angular, or Vue.js) for more advanced SPAs with features like routing, state management, and component-based architecture.