Optimize Specific Images For Mobile Devices With Responsive Design

Mobile devices have surpassed desktop usage. The approach developers take must adjust to these changes in usage behavior.

I like to use responsive design principles to create solutions that adapt to a users device so that the site looks its best whether its viewed on a computer or a phone.
One issue related to responsive design is the mobile optimization of image file size and the tradeoff of image quality.

Why serve a mobile device an image sized 500×500 when the device viewport is not that wide?
By sending a larger image, you are wasting bandwidth sent from your server and received by a user. This slows the session down because the larger images must be downloaded and then scaled down to the proper size.

Why not just serve a smaller image with a smaller file size?

I would assume there are plugins in the WordPress Repository that will do something similar, but I want to create something that is lightweight and will use core WordPress Functions to create a solution that will work in any environment.

1. Add Custom Images Sizes Specifically Optimized For Your Theme

if ( function_exists( 'add_image_size' ) ) { 
  add_image_size( 'rjs_port_image_full' , 475 );   //475 pixels wide (and unlimited height)
  add_image_size( 'rjs_port_image_lg', 215 );    //215 pixels wide (and unlimited height)

2. Call Mobile Specific Images With WP_is_mobile
This core function detects for mobile devices and displays a different output if the device is mobile.

if ( 
wp_is_mobile() ) {
  the_post_thumbnail('rjs_port_image_lg', array('class' => 'rjs-single-port-image'));
  the_post_thumbnail('full', array('class' => 'rjs-single-port-image'));

This if/else statement uses wp_is_mobile to test if the device is mobile, if it is then the 215px wide rjs_port_image_lg will be returned, otherwise, the 475px rjs_post_image_full will be displayed.
Both have a class added to them using array('class' => 'rjs-single-port-image').

Leave a Reply

Your email address will not be published. Required fields are marked *