点击无刷新更新页面URL的实现技术咨询——以stonestyle.co.th为例
Great question! Let’s break down exactly how that smooth, no-refresh navigation you’re seeing works—it’s not a choice between Ajax and HTML History API, but a combination of both. Here’s the play-by-play:
1. The HTML5 History API: Changing the URL Without Refreshing
This is the piece that lets the browser’s address bar update without triggering a full page reload. Two key methods make this happen:
history.pushState(stateObj, title, newUrl): Adds a new entry to the browser’s history stack and updates the URL. This is what lets users click back/forward and still see the correct URL state.history.replaceState(stateObj, title, newUrl): Updates the current history entry instead of adding a new one (useful for things like filtering content where you don’t want a new history entry).
Crucially, calling these methods doesn’t load any new content—it just updates the URL and history. That’s where the second piece comes in.
2. Ajax/Fetch API: Loading Content Asynchronously
To actually show new page content without refreshing, the site uses an asynchronous request (traditionally Ajax, now often the modern Fetch API) to grab the necessary content from the server. For example:
- When you click a navigation link, the site first stops the default browser behavior (which would normally reload the page).
- It sends a background request to the server for the HTML of the target page (or just the main content fragment, to save bandwidth).
- Once the content is fetched, it replaces the relevant part of the current page’s DOM (like the main content area) with the new content.
3. Putting It All Together (Like stonestyle.co.th)
Here’s the step-by-step flow for that site’s navigation:
- You click a menu item → the site intercepts the click (prevents default page load).
- It uses Fetch to get the new page’s content from the server.
- It uses
history.pushState()to update the address bar to the new URL. - It swaps out the old page content with the newly fetched content, often adding smooth transitions to make the experience feel seamless.
- To handle browser back/forward buttons, the site listens for the
popstateevent. When this event fires (user navigates history), it fetches the content corresponding to the previous/next URL and updates the DOM again.
Bonus: Modern Frameworks Build On This
If you’ve used React Router, Vue Router, or Next.js’s client-side navigation, they all use this exact combination under the hood—they just abstract the complexity into easy-to-use components and APIs.
内容的提问来源于stack exchange,提问作者Yordan Kostadinov

