How to Implement AJAX Without Killing Your SEO and Accessibility Efforts

by Rochester Oliveira

on August 5, 2013

in SEO

Get the FlatPix UI Kit for only $7 - Learn More or Buy Now

In the past few years we’ve seen a lot of changes in this big World Wide Web land, with a lot of different emerging devices, techniques and tools. HTML5, AJAX, Accessibility are the kind of stuff that just didn’t exist back when things were simpler, websites were created using front page and table tables were used to structure your layout.

A few things may sound pretty crazy now, like this old habit of creating websites using tables, but others are just equally crazy and people are still doing it, like obtrusive JavaScript.

JavaScript can be used in so many ways (especially after jQuery emerged as a must-have tool in any site) that sometimes we forget one simple and important thing: it will eventually break. Yeah, it’s that simple, one day or another it will just break.

The difference between Jedi Masters and Padawans is how prepared you are for those hard times when things don’t work as you wanted to.

Today we’ll see how obtrusive JS affects SEO, accessibility, the overall user experience and, of course, how to fix that in your sites using AJAX or even the awesome PJAX library.

Why JS can be bad for SEO and Accessibility

Google has certainly improved their tools and algorithms over time, adding the incredible ability of reading simple JS and even Flash (swf) animations. But the truth is, it still have a hard time with complex code.

For example, this code can easily be understood:

<a onclick="document.location.href='http://mysite.com'">

Google will just understand “Hey, I have to add this page to my crawling list, since document.location is a different way to load a new page”. Easy, right? But what if we do this:

<a onclick="openMyPage()">

Much harder, huh? You can imagine how the complexity increase when we’re talking about entire sites being loaded using AJAX, like portfolios, infinite loading pages, contact information. All this data is potentially hidden to Google.

Another important point is Accessibility (tough SEO is part of the accessibility field). Most people think that Accessibility refers only to “disabled” people, but I prefer a broader approach of “people with disability”, which means not only permanent disability like low vision but also temporarily or device-related disability, like using a mobile device or using an old browser.

Long story short, when you consider accessibility you make sure that most people will be able to access the content of your site, and not only the ones in the same conditions that you use or you have tested.

This is an interesting approach because it has zero cost (since it’s mostly a mindset) therefore it gives you infinite ROI (zero cost equals infinite return).

Here are a few things to consider:

  • Mobile devices – Not only “top” mobile devices (iPhone, s4, s3…) but also other common devices that still being used depending on your market (developing countries for instance still have a wide share of text-only mobile browsers)
  • Touch devices – Including tablets, smartphones
  • Different browsers – Beyond the “Firefox, IE, Chrome” checklist,  add also Safari, Opera, Android Browser, Firefox mobile and many, many others
  • Text-only browsing – Crawlers (like googlebot) only get the text so they don’t actually “process” the code in your page, same thing happens with some screen readers and other browsing conditions

All these different scenarios are fine when you have only plain HTML, so well written pages can be easily accessed even with their CSS disabled. But they certainly have a bad time processing JS so, I should say this one more time, that’s why sooner or later it’ll break.

But should we just remove it completely of our lives? Of course not!

Let’s see how to use it wisely now.

AJAX for dummies

The magic behind AJAX is that it loads the content without reloading the page. That is pretty good for the user experience, reducing load times and giving the developer the control over how the content is added in the page. But that can be bad also, since it relies on the JS to read XML content.

A simple login form can be written this way:

<form id="login">
    <input type="text" name="user" id="user" />
    <input type="password" name="password" id="password" />
</form>
<script type="text/javascript">
    $('form#login').submit(function(){
            $.post(
                'doLogin.php',
                {
                    'user': $('#user').val(),
                    'passwd': $('#password').val()
                }
            );
        }
    });
</script>

Can you see what’s wrong here? It’s relying completely on the JS to do the form processing. Just disable the JS and your life will be much harder. I’m not saying that a lot of users have JS disabled but you always should be ready for those extreme cases mentioned before, where it will simply break.

This is a simple change in your form that will fix it:

<form id="login" action="doLogin.php" method="POST">
    <input type="text" name="user" id="user" />
    <input type="password" name="password" id="password" />
    <input type="submit" />
</form>
<script type="text/javascript">
    $('form#login').submit(function(e){
            event.preventDefault();
            $.post(
                'doLogin.php',
                {
                    'user': $('#user').val(),
                    'passwd': $('#password').val()
                }
            );
        }
    });
</script>

This code will work either way, but JS (using the preventDefault) will stop the default action and will do an awesome action the way you wanted it to.

But let’s dig deeper, using PJAX you can take the unobtrusive approach to the next level!

The bright new path: PJAX

The main issue with entire sites loaded using AJAX is that you can only have urls with anchors (like #about), but you can’t have different paths (like /about) because AJAX alone wouldn’t be able to handle those URLs. As you can imagine this is bad for SEO, even if you use the unobtrusive approach you’ll have your entire content in a single page so Google will only refer to one page.

That’s when PJAX arrives to save us all.

PJAX allows you to add a PushState layer above the AJAX calls. What does it mean? It means that you can add paths and actually change browser history. That’s pretty much the same thing as Gmail does, where the content is loaded using JS but you can actually use the back button of your browser, or type the url of your desired label or email (if you remember its ID).

What you need to do is to download it in the PJAX project page, and then you can call a script like this one:

<script type="text/javascript">
    pjax.connect({
        'container': 'login',
        'beforeSend': function(){ alert("This alert will be shown before loading content")},
        'complete': function(){ alert("And this one goes afterwards") }
    });
</script>

The main difference is in the server side, now you have a $_SERVER[‘HTTP_X_PJAX’] variable set as true, so in your CMS you can conditionally test for this variable, if it’s true, only the current content will be loaded, if it’s false you’ll create an entire new page since the user is not using JS (or it’s broken, or something went wrong with the request). Like this:

<?php
        if($_SERVER['HTTP_X_PJAX'] == true){
            echo $only_main_div_content;
        } else {
            echo $the_entire_page;
        }
?>

That’s pretty cool and if you are using a CMS you can give a whole new experience to your users without affecting your SEO since you always have you “plan B” with the regular content.

Summing up

Today we’ve seen how it’s possible to improve user experience AND your site accessibility without hurting your SEO. What do you think about this? Do you know any other library that we could use? Let us know using the comments section!

Powered by Shutterstock

About Rochester Oliveira

Roch is a web designer and entrepreneur from Itajubá (MG), Brasil. He loves writing about obscure topics and doing some cool stuff. Connect with Roch on Google +