Conditional content loading in WordPress with AJAX, Part 1 – The Setup

“Lazy loading” (also called Conditional Loading) of content is becoming more and more common these days. It enables us to enhance performance by delaying the loading of purely decorative or nice-to-have page enhancements so that the core content arrives to the user more quickly.

Another advantage of waiting until after the initial page load for certain content is that we have a chance to gather some information about the user’s environment (screen size, browser features, etc) before we send the code for the enhanced content. This enables us to tailor the experience to the device using our web site. If features aren’t supported, we just won’t load them at all and save that user from downloading a bunch of files they can’t use.

Since conditional loading uses Javascript, devices without Javascript will not receive any of the new features or content we’ll be loading, so we must make sure that the base experience is completely functional and that we are not relying on Javascript to load critical content. (Some of this thought process is discussed here).

For my purposes here, I will be loading images into a slide show using two different image sizes according to the size of the browser window.

I develop site almost exclusively with WordPress, so this procedural description covers the way I have learned to conditionally load images using AJAX (Asynchronous Javascript and XHTML) in a WordPress theme.

AJAX was mind-bendingly difficult for me to get my head around, and the big picture is still a little shaky. I’m not a brilliant master of Javascript or PHP or anything like that, and I’m still refining my procedures every time I implement something like this, so please forgive me if my code or my thinking is a little clunky at times. I welcome improvements and suggestions.

This article by Gary Cao on AJAX in WordPress was very helpful in guiding me along, and I use some snippets of Gary’s code in the samples that follow.

The basic flow is this:

  1. Our functions.php file registers and enqueues our Javascript file and an extra bit of code enables us to give the Javascript file any information it might need (most often just the post ID of the page we’re on).
  2. Our Javascript file checks the size of the browser window and sends a request back to our functions.php file along with the post ID and any other info we’ve given it.
  3. In functions.php, we have a function that receives the message from the Javascript, queries the database and returns the required HTML markup.
  4. Our Javascript receives the markup from our php function and inserts it into the document.

Set up the environment in functions.php

If our theme doesn’t already provide a Javscript file for us to work with, we add one using wp_register_script() and wp_enqueue_script(). I most often use the Bones starter theme as my starting point, which already enqueues “scripts.js” in the “library/js” directory.

Inside the php function that enqueues the script, use wp_localize-script() to allow us to pass variables from the Javascript to the database query later on:

// add Ajax URl variable, from http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/
wp_localize_script( 'bones-js', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

‘bone-js’ is the name of the script as we registered it with wp_register_scripts(). ‘MyAjax’ is a handy reference name that we will use in our Javascript file to identify the variables later on. The last bit points to some of WordPress’s AJAX functions.

In a new section of functions.php set aside for the AJAX functionality, add these actions. I’m still not quite sure exactly how these work, but they help bridge the gap between the PHP and Javascript. You only need to include these once to enable as many AJAX operations as needed for the site.

// THESE ARE FOR ALL THE AJAX CALLS!
// adapted from http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/
// this hook is fired if the current viewer is not logged in
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );

// if logged in:
do_action( 'wp_ajax_' . $_POST['action'] );

Put the Post ID in the HTML

Our request for these images takes a weird route, from the Javascript to the PHP and back. The request starts with the Javascript, but unlike our normal WordPress templates, it doesn’t have direct access to the database so it has no easy way to reference the post ID. In order to get the images that we want, we have to put that ID somewhere in the HTML so the Javascript can grab it and pass it back to the server in our AJAX request. The easiest way I could think of is to insert the post ID as a data attribute in the body element.

So I add a data-id attribute to the body element in the header.php template:

<body data-id="<php the_ID(); ?>" <?php body_class(); ?>>

That completes the initial setup for our AJAX requests in PHP.

In the next article, we’ll go over the Javascript required to initiate the request and then insert the received data into the page.