Carousels/sliders are one of the most widely used widgets in development for the Web today (although the debate over using them still varies in opinion). In my experience w/sliders there’s literally no need to load every single image for a slider on init window load. Today I share my implementation for a client project brought to me by Staple Web Design using WordPress and Flexslider (which does not support lazy loading out of the box).
In this particular case, the client can use the Media Uploader found on a post’s editor screen. As you can see in figure 1 the post allows multiple images to be inserted into the custom post we’ve created. Once the images are within the post as attachments we can run a loop in our PHP to grab the images and display them within our desired markup pattern.
The PHP seen in figure 2 is placed within single-rvs.php which is a custom post type (called ‘rvs’) template. We use the get_children() method to grab all the image attachments for the post, grab our image sources and finally inject them accordingly. In order to display the thumbnails portion we must duplicate the top slider markup so we can sync both sections as documented by Flexslider. Now we can grab the “full” size image for the main slider (large single images) and for the carousel (smaller thumbnail images) we retrieve the “medium” size. This is one of the benefits of using WordPress’ Media Uploader as it will generate different sizes for each image uploaded. Using this approach we can use smaller files for the thumbnails and larger images for the main showcase slides. Makes sense right?
Lazy Loading Media
In the bottom of our document (just before the closing body tag) we load the Flexslider library followed by the custom config. The actual call for the entire config is wrapped in a window.load event so we can make sure the DOM is loaded as quickly as possible and not blocking page load. This way we create a perceived performance improvement for users by loading only a few images at once and lazily loading the rest after the window load event occurs.
Within our config we call window.load and then a call to the Flexslider using some keys given to us by the Flexslider API and of course set our options accordingly. The following will only load the first two main gallery images at full size and finally load the first 3 thumbnails as medium image attachments lazily. Each time a slide advances it loads the next slide image in the series. This way we pre-load ahead of time and make the experience that much faster for the user.