A place to cache linked articles (think custom and personal wayback machine)
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

4 anos atrás
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. title: History API - Dive Into HTML5
  2. url: http://diveintohtml5.info/history.html
  3. hash_url: 897f370c439ad4b431206ec71e5dc4fa
  4. <p class="f">The browser location bar is perhaps the geekiest mainstream piece of user interface in the world. There are <abbr>URL</abbr>s on billboards, on the sides of trains, and even in street graffiti. Combined with the back button — easily the most important button in the browser — you have a powerful way to go forward and backward through the vast set of intertwingled resources called the Web.
  5. </p><p>The <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html"><abbr>HTML5</abbr> history <abbr>API</abbr></a> is a standardized way to manipulate the browser history via script. Part of this <abbr>API</abbr> — navigating the history — has been available in previous versions of <abbr>HTML</abbr>. The new parts in <abbr>HTML5</abbr> include a way to add entries to the browser history, to visibly change the <abbr>URL</abbr> 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. This means that the <abbr>URL</abbr> in the browser location bar can continue to do its job as a unique identifier for the current resource, even in script-heavy applications that don’t ever perform a full page refresh.
  6. </p><h2 id="why">The Why</h2>
  7. <p class="ss"><img src="http://diveintohtml5.info/i/openclipart.org_johnny_automatic_demon_reading_Stewart_Orr.png" alt="demon reading book" width="218" height="231"/>
  8. </p><p>Why would you manually manipulate the browser location? After all, a simple link can navigate to a new <abbr>URL</abbr>; that’s the way the web has worked for 20 years. And it will continue to work that way. This <abbr>API</abbr> doesn’t try to subvert the web. Just the opposite. In recent years, web developers have found new and exciting ways of subverting the web without any help from emerging standards. The <abbr>HTML5</abbr> history <abbr>API</abbr> is actually designed to ensure that <abbr>URL</abbr>s continue to be useful in script-heavy web applications.
  9. </p><p>Going back to first principles, what does a <abbr>URL</abbr> do? It identifies a unique resource. You can link to it directly; you can bookmark it; search engines can index it; you can copy and paste it and email it to someone else, who can click it and end up seeing the same resource you saw originally. These are all excellent qualities. <abbr>URL</abbr>s matter.
  10. </p><p>So we want unique resources to have unique <abbr>URL</abbr>s. But at the same time, browsers have always had a fundamental limitation: if you change the <abbr>URL</abbr>, 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 <abbr>URL</abbr> but only download half a page.
  11. </p><p>The <abbr>HTML5</abbr> history <abbr>API</abbr> lets you do this. Instead of triggering a full page refresh, you can use script to, in essence, download half a page. This illusion is tricky to pull off, and it requires some work on your part. Are you watching closely?
  12. </p><p class="ss"><img src="http://diveintohtml5.info/i/openclipart.org_johnny_automatic_card_trick.png" width="287" height="238" alt="magician performing a card trick"/>
  13. </p><p id="illusion">Let’s say you have two pages, page A and page B. The two pages are 90% identical; only 10% of the page content is different. The user navigates to page A, then tries to navigate to page B. But instead of triggering a full page refresh, you interrupt this navigation and do the following steps manually:
  14. </p><ol>
  15. <li><em>Load the 10% of the page</em> from page B that is different from page A (probably using <code>XMLHttpRequest</code>). This will require some server-side changes to your web application. You will need to write code to return just the 10% of page B that is different from page A. This can be a hidden <abbr>URL</abbr> or query parameter that the end user would not normally see.
  16. </li><li><em>Swap in the changed content</em> (using <code>innerHTML</code> or other <abbr>DOM</abbr> methods). You may also need to reset any event handlers on elements within the swapped-in content.
  17. </li><li><em>Update the browser location bar</em> with the <abbr>URL</abbr> of page B, using a particular method from the <abbr>HTML5</abbr> history <abbr>API</abbr> that I’ll show you in a moment.
  18. </li></ol>
  19. <p>At the end of this illusion (if you executed it correctly), the browser ends up with a <abbr>DOM</abbr> that is identical to page B, just as if you had navigated to page B directly. The browser location bar ends up with a <abbr>URL</abbr> that is identical to page B, just as if you had navigated to page B directly. But you never really did navigate to page B, and you never did a full page refresh. That’s the illusion. But because the “compiled” page looks the same as page B and has the same <abbr>URL</abbr> as page B, the user should never notice the difference (nor appreciate all your hard work micromanaging their experience).
  20. </p><p class="a rotatedFloralHeartBullet">
  21. </p><h2 id="how">The How</h2>
  22. <p>The <abbr>HTML5</abbr> history <abbr>API</abbr> is just a handful of methods on the <code>window.history</code> object, plus one event on the <code>window</code> object. You can use these to <a href="http://diveintohtml5.info/detect.html#history">detect support for the history <abbr>API</abbr></a>. Support is currently limited to the very latest versions of a few browsers, putting these techniques squarely in the “progressive enhancement” camp.
  23. </p><table class="bc">
  24. <caption>history.pushState support</caption>
  25. <thead>
  26. <tr><th title="Internet Explorer">IE</th><th title="Mozilla Firefox">Firefox</th><th title="Apple Safari">Safari</th><th title="Google Chrome">Chrome</th><th>Opera</th><th>iPhone</th><th>Android
  27. </th></tr></thead><tbody>
  28. <tr><td>·</td><td>4.0+</td><td>5.0+</td><td>8.0+</td><td>11.50+</td><td>4.2.1+</td><td>·
  29. </td></tr></tbody></table>
  30. <p><a href="http://diveintohtml5.info/examples/history/fer.html">dive into dogs</a> is a straightforward but non-trivial example of using the <abbr>HTML5</abbr> history <abbr>API</abbr>. It demonstrates a common pattern: a long article with an associated inline photo gallery. In a supported browser, navigating the Next and Previous links in the photo gallery will update the photo in place <em>and update the <abbr>URL</abbr> in the browser location bar</em>, without triggering a full page refresh. In unsupported browsers — or, indeed, supported browsers where the user has disabled scripting — the links simply function as regular links, taking you to a new page with a full page refresh.
  31. </p><p id="gallery-markup">Let’s dig into the <a href="http://diveintohtml5.info/examples/history/fer.html">dive into dogs</a> demo and see how it works. This is the relevant markup for a single photo:
  32. </p><p class="legend top"><span class="arrow anticlockwiseTopSemicircleArrow"/> The pledge
  33. </p><pre><code>&lt;aside id="gallery"&gt;
  34. &lt;p class="photonav"&gt;
  35. &lt;a id="photonext" href="http://diveintohtml5.info/casey.html"&gt;Next &amp;gt;&lt;/a&gt;
  36. &lt;a id="photoprev" href="http://diveintohtml5.info/adagio.html"&gt;&amp;lt; Previous&lt;/a&gt;
  37. &lt;/p&gt;
  38. &lt;figure id="photo"&gt;
  39. &lt;img id="photoimg" src="http://diveintohtml5.info/gallery/1972-fer-500.jpg"
  40. alt="Fer" width="500" height="375"&gt;
  41. &lt;figcaption&gt;Fer, 1972&lt;/figcaption&gt;
  42. &lt;/figure&gt;
  43. &lt;/aside&gt;</code></pre>
  44. <p>Nothing unusual there. The photo itself is an <code>&lt;img&gt;</code> inside a <code>&lt;figure&gt;</code>, the links are just regular <code>&lt;a&gt;</code> elements, and the entire thing is wrapped in an <code>&lt;aside&gt;</code>. It’s important that these are just regular links that actually work. All the code that follows is behind a <a href="http://diveintohtml5.info/detect.html#history">detection script</a>. If the user is using an unsupported browser, none of our fancy history <abbr>API</abbr> code will ever be executed. And of course, there’s always some users with scripting disabled altogether.
  45. </p><p>The main driver function gets each of these links and passes it to a function, <code>addClicker()</code>, which does the actual work of setting up the custom <code>click</code> handler.
  46. </p><pre><code>function setupHistoryClicks() {
  47. addClicker(document.getElementById("photonext"));
  48. addClicker(document.getElementById("photoprev"));
  49. }</code></pre>
  50. <p>This is the <code>addClicker()</code> function. It takes an <code>&lt;a&gt;</code> element and adds a <code>click</code> handler. And within this <code>click</code> handler is where it gets interesting.
  51. </p><pre><code>function addClicker(link) {
  52. link.addEventListener("click", function(e) {
  53. swapPhoto(link.href);
  54. history.pushState(null, null, link.href);
  55. e.preventDefault();
  56. }, false);
  57. }</code></pre>
  58. <p class="legend right"><span class="arrow leftwardsWaveArrow"/> Interesting
  59. </p><p>The <code>swapPhoto()</code> function performs the first two steps of our <a href="http://diveintohtml5.info/#illusion">three-step illusion</a>. The first half of the <code>swapPhoto()</code> function takes part of the <abbr>URL</abbr> of the navigation link itself — <code>casey.html</code>, <code>adagio.html</code>, <i>&amp;</i>c. — and constructs a <abbr>URL</abbr> to a hidden page that contains nothing but the markup required by the next photo.
  60. </p><pre><code>function swapPhoto(href) {
  61. var req = new XMLHttpRequest();
  62. req.open("GET",
  63. "http://diveintohtml5.info/examples/history/gallery/" +
  64. href.split("/").pop(),
  65. false);
  66. req.send(null);</code></pre>
  67. <p>Here is a sample of the markup returned by <code><a href="http://diveintohtml5.info/examples/history/gallery/casey.html">http://diveintohtml5.info/examples/history/gallery/casey.html</a></code>. (You can verify this in your browser by visiting that <abbr>URL</abbr> directly.)
  68. </p><pre><code>&lt;p class="photonav"&gt;
  69. &lt;a id="photonext" href="http://diveintohtml5.info/brandy.html"&gt;Next &amp;gt;&lt;/a&gt;
  70. &lt;a id="photoprev" href="http://diveintohtml5.info/fer.html"&gt;&amp;lt; Previous&lt;/a&gt;
  71. &lt;/p&gt;
  72. &lt;figure id="photo"&gt;
  73. &lt;img id="photoimg" src="http://diveintohtml5.info/gallery/1984-casey-500.jpg"
  74. alt="Casey" width="500" height="375"&gt;
  75. &lt;figcaption&gt;Casey, 1984&lt;/figcaption&gt;
  76. &lt;/figure&gt;</code></pre>
  77. <p>Does that look familiar? It should. It’s the <a href="http://diveintohtml5.info/#gallery-markup">same basic markup that the original page used</a> to display the first photo.
  78. </p><p>The second half of the <code>swapPhoto()</code> function performs the second step of our <a href="http://diveintohtml5.info/#illusion">three-step illusion</a>: inserting this newly downloaded markup into the current page. Remember that there is an <code>&lt;aside&gt;</code> wrapping the entire figure, photo, and caption. So inserting the new photo markup is a one-liner, setting the <code>innerHTML</code> property of the <code>&lt;aside&gt;</code> to the <code>responseText</code> property returned from <code>XMLHttpRequest</code>.
  79. </p><pre><code> if (req.status == 200) {
  80. document.getElementById("gallery").innerHTML = req.responseText;
  81. setupHistoryClicks();
  82. return true;
  83. }
  84. return false;
  85. }</code></pre>
  86. <p>(Also notice the call to <code>setupHistoryClicks()</code>. This is necessary to reset the custom <code>click</code> event handlers on the newly inserted navigation links. Setting <code>innerHTML</code> wipes out any trace of the old links and their event handlers.)
  87. </p><p>Now, let’s go back to the <code>addClicker()</code> function. After successfully swapping out the photo, there’s one more step in our <a href="http://diveintohtml5.info/#illusion">three-step illusion</a>: setting the <abbr>URL</abbr> in the browser location bar without refreshing the page.
  88. </p><p class="legend top"><span class="arrow anticlockwiseTopSemicircleArrow"/> The turn
  89. </p><pre><code>history.pushState(null, null, link.href);</code></pre>
  90. <p>The <code>history.pushState()</code> function takes three parameters:
  91. </p><ol>
  92. <li><code>state</code> can be any <abbr>JSON</abbr> data structure. It is passed back to the <code>popstate</code> event hander, which you’ll learn about in just a moment. We don’t need to track any state in this demo, so I’ve left it as <code>null</code>.
  93. </li><li><code>title</code> 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 <code>state</code> argument and set it manually in your <code>popstate</code> callback.
  94. </li><li><code>url</code> can be, well, any <abbr>URL</abbr>. This is the <abbr>URL</abbr> you want to appear in the browser’s location bar.
  95. </li></ol>
  96. <p>Calling <code>history.pushState</code> will immediately change the <abbr>URL</abbr> in the browser’s location bar. So is that the end of the illusion? Well, not quite. We still need to talk about what happens when the user presses the all-important back button.
  97. </p><p>Normally when the user navigates to a new page (with a full page refresh), the browser pushes the new <abbr>URL</abbr> 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. But what happens now that you’ve short-circuited this navigation to avoid a full page refresh? Well, you’ve faked “moving forward” to a new <abbr>URL</abbr>, so now you also need to fake “moving backward” to the previous <abbr>URL</abbr>. And the key to faking “moving backwards” is the <code>popstate</code> event.
  98. </p><p class="legend top"><span class="arrow anticlockwiseTopSemicircleArrow"/> The prestige
  99. </p><pre><code>window.addEventListener("popstate", function(e) {
  100. swapPhoto(location.pathname);
  101. });</code></pre>
  102. <p>After you’ve used the <code>history.pushState()</code> function to push a fake <abbr>URL</abbr> onto the browser’s history stack, when the user presses the back button, the browser will fire a <code>popstate</code> event on the <code>window</code> object. This is your chance to complete the illusion once and for all. Because making something disappear isn't enough; you have to bring it back.
  103. </p><p>In this demonstration, “bringing it back” is as simple as swapping in the original photo, which we do by calling the <code>swapPhoto()</code> with the current location. By the time your <code>popstate</code> callback is called, the <abbr>URL</abbr> visible in the browser’s location bar has been changed to the previous <abbr>URL</abbr>. Also, the global <code>location</code> property has already been updated with the previous <abbr>URL</abbr>.
  104. </p><p>To help you visualize this, let’s step through the entire illusion from the beginning to the end:
  105. </p><ul>
  106. <li>User loads <code><a href="http://diveintohtml5.info/examples/history/fer.html">http://diveintohtml5.info/examples/history/fer.html</a></code>, sees story and a photo of Fer.
  107. </li><li>User clicks the link labeled “Next,” an <code>&lt;a&gt;</code> element whose <code>href</code> property is <code><a href="http://diveintohtml5.info/examples/history/casey.html">http://diveintohtml5.info/examples/history/casey.html</a></code>.
  108. </li><li>Instead of navigating <code><a href="http://diveintohtml5.info/examples/history/casey.html">http://diveintohtml5.info/examples/history/casey.html</a></code> with a full page refresh, the custom <code>click</code> handler on the <code>&lt;a&gt;</code> element traps the click and executes its own code.
  109. </li><li>Our custom <code>click</code> handler calls the <code>swapPhoto()</code> function, which creates an <code>XMLHttpRequest</code> object to synchronously download the <abbr>HTML</abbr> snippet located at <code><a href="http://diveintohtml5.info/examples/history/gallery/casey.html">http://diveintohtml5.info/examples/history/<strong>gallery</strong>/casey.html</a></code>.
  110. </li><li>The <code>swapPhoto()</code> function sets the <code>innerHTML</code> property of the photo gallery wrapper (an <code>&lt;aside&gt;</code> element), thereby replacing the captioned photo of Fer with a captioned photo of Casey.
  111. </li><li>Finally, our custom <code>click</code> handler calls the <code>history.pushState()</code> function to manually change the <abbr>URL</abbr> in the browser’s location bar to <code><a href="http://diveintohtml5.info/examples/history/casey.html">http://diveintohtml5.info/examples/history/casey.html</a></code>.
  112. </li><li>User clicks the browser’s back button.
  113. </li><li>The browser notices that a <abbr>URL</abbr> has been manually pushed onto the history stack (by the <code>history.pushState()</code> function). Instead of navigating to the previous <abbr>URL</abbr> and redrawing the entire page, the browser simply updates the location bar to the previous <abbr>URL</abbr> (<code><a href="http://diveintohtml5.info/examples/history/fer.html">http://diveintohtml5.info/examples/history/fer.html</a></code>) and fires a <code>popstate</code> event.
  114. </li><li>Our custom <code>popstate</code> handler calls the <code>swapPhoto()</code> function again, this time with the previous <abbr>URL</abbr> that by now is already visible in the browser’s location bar.
  115. </li><li>Again using <code>XMLHttpRequest</code>, the <code>swapPhoto()</code> function downloads a snippet of <abbr>HTML</abbr> located at <code><a href="http://diveintohtml5.info/examples/history/gallery/fer.html">http://diveintohtml5.info/examples/history/<strong>gallery</strong>/fer.html</a></code> and sets the <code>innerHTML</code> property of the <code>&lt;aside&gt;</code> wrapper element, thereby replacing the captioned photo of Casey with a captioned photo of Fer.
  116. </li></ul>
  117. <p>The illusion is complete. All visible evidence (the content of the page, and the <abbr>URL</abbr> in the location bar) suggests to the user that they have navigated forward one page and backward one page. But no full page refresh ever occurred — it was all a meticulously executed illusion.
  118. </p>