mercoledì 9 gennaio 2013

The Pinterest Url Sorcery: How Pinterest changes the url with just an AJAX call.

Before starting i need to tell you first: I do not have a Pinterest account and I'm not looking forward to create one in the future.

A reason why I'll never use Pinterest.

Despite that the Pinterest's homepage caught my attention:

There's a loads and loads of "pinned" (what a horrible verb) articles. When someone cliks on one of them, a popup comes out with the details of the article loaded by AJAX. The sorcery is the fact that in the same time the URL CHANGES AS WELL: that's really cool in a SEO prospective. In top of that, if you try to copy and paste the changed url in another tab of the browser you'll get a stand-alone page of the same article.

To achieve this we need to focus on two main topics:

  • Changing the Url without a HTML call
  • Manage in the same url the Full HTML document and a JSON object (or a partial HTML response)

Let's start with the first one:

 Link First Pin
 Link Second Pin

the magic is done through History API of HTML 5:

"history.pushState(, tit," is the key instruction that allows us to change the url and add it into the navigation history without an actual page refresh.

The event "popstate" instead is raised at the first loading of the page and everytime we go back to the browsing history (so "popping out" the previous history pushed before by the pushState function) and allows us to recreate the same page using the value stored in "e.state" by the first argument of "pushState".

About the second topic, all you need to do is to handle GET requests in the same url in two different ways depending if the value of the HTTP header "X-Requested-With" is set to "XMLHttpRequest"or not: in the first case, you'll need to return a JSON object (or a partial HTML code), else a normal XHTML document.

This can be easily done in WebForms by making a call to the function Server.Transfer to the "partial response" or in ASP.NET MVC returning a different type of ActionResult ("Content" and "Json" for instance instead of "View")

Summarizing that:

  • in your web application, handle with the same url a normal HTML document and a JSON/partial response if the header "X-Requested-With"is set to "XMLHttpRequest"
  • handle the click of the anchor calling history.pushState to modify the url and the navigation history without an actual page refresh.
  • handle the "popstate" event to load the same informations using the "e.state" passed by the first argument of the function pushState.

For more informations about History API click here or here.

Nessun commento:

Posta un commento