Alright so AJAX is a great tool and invaluable for any front end developer to have in their toolbelt.  The problem comes in when you want to provide content via AJAX throughtout a whole site. (AJAX is used loosely as a term for using JavasScript to load data from other sources without a page need to be redrawn)  This creates a big problem when it comes to search engines because they cannot scrape a site that has been filled dynamically with JavaScript.  A search engine is expecting a more typical site structure with links to pages to new content and subdirectories for microsites and deeper levels of a site to understand it’s structure.

If it is the AJAX feel that is desired, a swapping out of content without redrawing the whole page then that can still be done with AJAX but it will pull content from actualy pages themselves and just pull and swap what is needed.  This creates a nice fallback for people who may be disabling javascript as well.  There is still a full site that is built and functional which is also what a search engine can crawl.  This allows search engines to understand the site structure as well as any lower level content.  Otherwise search engines can only grab the content that is on the homepage of a site if it has been hard coded into the markup.

Getting to the Code

If you already have a typical site in place without any javascript handling the content of pages then it only takes a few things to get this up and running.

Attach an event handler to all internal links.

  1. Prevent default click action from navigating to the new page.
  2. Catch the url the link was originally linking to.
  3. Open an AJAX request to load that url.
  4. Select just the desired content to pull from the page
  5. Replace the data on the current page.

So the code would look like this:

(the hash tag is being set to the value of the id for the content div. Just here to show that a new page is not being hit.)

var $content = $('#content');

$('nav a').click(function(e){
	var $page = $(this).attr('href');
	$content.load($page + ' #content');
	window.location.hash = $page;

Example Here

Full Source