“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.
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.
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:
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.
// 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' ) ) );
// 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
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.