Posts and Pages Tagged ‘ajax’

Loading a webpage in stages Last updated:29 October 2010

I reworked my homepage this weekend and wanted to display the latest WordPress blog post on it. No problem there. However, the initial response times for my blog are sometimes quite slow, and this then meant that the whole of my homepage was slow to display, because the page was waiting for the blog to respond before displaying anything.

So what I wanted to do was display the home page immediately, and then load the blog post when it’s available. The solution was to use AJAX, which turned out to be very straightforward. More information on AJAX here, but essentially it allows a page to communicate with a server without refreshing the whole page.

First things first – here’s the php code to retrieve the latest post from WordPress as follows (I originally had this on the homepage itself):

<?php require($_SERVER['DOCUMENT_ROOT']."/blog/wp-blog-header.php");
while (have_posts()): the_post();?> 
<h2><a href="<?php the_permalink(); ?>" title="Blog">
Latest blog: <?php the_title(); ?></a></h2>
<?php the_excerpt(); ?>
<?php endwhile;?>

I saved this code separately into a file called latest_post.php (stored in my “includes” folder).

In my homepage file I added some “placeholder” code where I want the blog post to appear. This will be displayed until the data comes back from WordPress:

<div id="latest_post">
<h2>Latest blog: loading...</h2>

Note the id of latest_post assigned to the div. Then I added the following javascript code to the <head> section of the homepage:

<script type="text/javascript">
window.onload = new Function("loadXMLDoc('/includes/latest_post.php');");
function loadXMLDoc(url)
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

The function loadXMLDoc retrieves the php file I’ve created above (latest_post.php) and then the last line replaces the text within the element with id “latest_post” with whatever is retrieved. This is standard ajax code which can be used for any purpose. Only the last line is specific to my page.

The code window.onload... calls this function when the page is loaded.

So, when the page is requested the php and html that’s on the page display the page with the placeholder text, but without the blog post, so the page loads nice and quickly. Once the page loads, the javascript is fired which calls the AJAX function to retrieve the blog post, and this loads on the page when it’s available.

This was the first time I’ve used AJAX, and it seemed quite a neat little solution, so I thought I’d post it here. This is the basic solution which could be further enhanced with some error handling.