[JavaScript] HTML Web History API Example
Change browser URL without reloading the whole web page - only partially update the content of the web page, improve the user experience of visiting your website. This is done via HTML history API.
I simplify the example in the tutorial of CSS-Tricks [3]. In the example below, I create three links, and if users click the link, the browser URL will change, and update the texts correspondingly without reloading. When users move backward or forward through the history, web page will also be partially updated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>JavaScript HTML History API Demo</title> </head> <body> <div><a class="person" href="/p1/" data-content="content of person 1">person 1</a></div> <div><a class="person" href="/p2/" data-content="content of person 2">person 2</a></div> <div><a class="person" href="/p3/" data-content="content of person 3">person 3</a></div> <hr> <div id="info">Entry Page</div> <script src="app.js"></script> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | "use strict"; var info = document.getElementById("info"); var persons = document.querySelectorAll(".person"); var i; for (i=0; i<persons.length; i++) { persons[i].addEventListener("click", function(event) { event.preventDefault(); var person = event.target; var href = person.getAttribute("href"); var content = person.dataset.content; window.history.pushState(content, null, href); info.innerHTML = content; }, false); } window.addEventListener("popstate",function(event) { if (event.state === null) { info.innerHTML = "Entry Page"; } else { info.innerHTML = event.state; } }, false); |
For GopherJS version, see [4].
Tested on:
- Ubuntu Linux 16.10
- Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)
References:
[1] | html history api - Google search html history api - DuckDuckGo search html history api - Bing search html history api - Yahoo search |
[2] | Manipulating the browser history - Web APIs | MDN |
[3] | Using the HTML5 History API | CSS-Tricks |
[4] | [GopherJS] HTML Web History API Example |