By Big Spaceship
Websites are more frequently using shebang (#!) as a method for switching pages using AJAX. Google has a whole spec for how to use this method but also allow your site to be indexable via crawlers. This article is going to argue, why do we need that at all?
Quick history on the shebang
If you already know about shebangs and their purpose, you can gloss over this section.
You may notice more popular websites like Facebook, Google, and Twitter are inserting these things in their URLs that looks like: http://twitter.com/#!/bigspaceship. Typically when the URL in the address bar changes, the entire page then reloads itself. However, when you add a “#” to it, the page does not reload. This is because the pound sign was used for jumping to different anchor elements on the page without refreshing. People often now use it to change content on the page without loading the entire site over again. This method uses AJAX to load only the new content.
Using the “#” alone will do the job, but Google has suggested using a shebang ”#!” instead. They say it becomes “AJAX crawlable” in this way and offer an elaborate system to which you can read data after the shebang. It’s their standard for combating the troubles posed by using this method. This can be read in full here.
Initial HTML Code
Adding the AJAX
So if all of our links are just standard, how does the AJAX come in to play? On the page load, you would loop through all your anchor elements and assign a click handler to intercept the URL switch. You can get the ”href” attribute inside your handler, insert a “#!/” between your domain and the request URI, and set the window.location to that new URL.
Don’t rewrite PHP
Some people are afraid that they’ll have to serve up two different sets of content if they use this sort of method, but you don’t. AJAX requests come with a server header of “HTTP_X_REQUESTED_WITH”. You can check for this and, instead of serving up a template, you serve up JSON encoded data.
It’s standard practice to set all of your data to an array or object, then pass that off to a view and let that populate itself. This method makes it really easy to check the $_SERVER['HTTP_X_REQUESTED_WITH'] value to toggle between die(json_encode($data)); and $template->render(‘myTemplate.html’, $data);
Some interesting reads
I don’t know how long some of these URLs will exist, but if you can read them, they’re pretty interesting: