Manipulating History for Fun & Profit

1.   The HTML5 history API is a standardized way to manipulate the browser history via script. Part of this API — navigating the history — has been available in previous versions of HTML . The new parts in HTML5 include a way to add entries to the browser history, to visibly change the URL in the browser location bar (without triggering a page refresh), and an event that fires when those entries are removed from the stack by the user pressing the browser’s back button.

 

 

2.   If you change the URL , even through script, it triggers a roundtrip to the remote web server and a full page refresh. This takes time and resources, and it seems especially wasteful when you are navigating to a page that is substantially similar to the current page. Everything on the new page gets downloaded, even the parts that are exactly the same as the current page. There is no way tell a browser to change the URL but only download half a page.

 

3.   The history.pushState() function takes three parameters:

  a)   state can be any JSON data structure. It is passed back to the popstate event hander.

  b)   title can be any string. This parameter is currently unused by major browsers. If you want to set the page title, you should store it in the state argument and set it manually in your popstate callback.

  c)  u rl can be, well, any URL. This is the URL you want to appear in the browser’s location bar.

Calling history.pushState will immediately change the URL in the browser’s location bar without a full page refresh. Normally when the user navigates to a new page (with a full page refresh), the browser pushes the new URL onto its history stack and downloads and draws the new page. When the user presses the back button, the browser pops one page off its history stack and redraws the previous page. history.pushState fakes “moving forward” to a new URL .

 

4.   After you’ve used the history.pushState() function to push a fake URL onto the browser’s history stack, when the user presses the back button, the browser notices that a URL has been manually pushed onto the history stack. Instead of navigating to the previous URL and redrawing the entire page, the browser simply updates the location bar to the previous URL fire a popstate event on the window object. By the time your popstate callback is called, the global location property has already been updated with the previous URL .

你可能感兴趣的:(history)