Monday, May 16, 2011

Making AJAX sites easily visible to search engines

I created a web site a short time ago: Wiltshire Architect Alex Somers. I had quite a bit of fun making the elements fade into each other rather than having an abrupt move from one page to the next. All was well, then I looked at Google's cache of the site. Oh dear, a pretty sparse page with no content. I had made a bit of a schoolboy error in forgetting that Google et al still crawl good ol' HTML, they don't tend (as a rule) to do Javascript. I needed some way of making the site degrade nicely. This works well for two situations. Apart from search engines, some luddites still believe that javascript is satan's code and turn it off. Whilst they're fools, I still want them to employ my client. So what to do? Well, to make my pages sloop into each other I had used anchors rather than pages in my hrefs. This meant that links looked like this:
<a href="#page=architectural_services&category=24">Survey</a>
My javascript then took the page and category variables and then expanded the appropriate menu entry, and put the appropriate content in the page.

I then converted all my links to look like this:
<a href="./architectural_services.php?category=24">Survey</a>
I then made a little javascript function (using dojo):

dojo.addOnLoad(reHash);

function reHash() {
dojo.forEach(dojo.query("a"), function(node) {
    var href = node.getAttribute("href");
    if ( dojo.isIE ) {
      href = href.replace("http://www.alexsomers.co.uk","");
      href = href.replace(/\//,"#page=");
      href = href.replace("#page=#page=","#page=");
    } else {
      href = href.replace(/\.\//,"#page=");
    }
    href = href.replace(/\?/,"&");
    href = href.replace(/\.php/,"");
    node.setAttribute("href",href);
  });
}

Of course, I then had to make some php pages which reflected what would have been done by javascript. It's been a valuable lesson, though. I'll look at ways of creating 'dual' content in my next post.