Main content area

Extending Drupal 8s templating options for responsive images

The client: NHS Orkney CMS: Drupal 8

The goal

Take advantage of Drupal's tools for controlling and optimising the size of images in order to optimise site's speed and performance on all devices.

What does the CMS do for this? 

Drupal has a powerful image manipulation system that allows for the creation of image styles that can perform various effects on an image and create a derivative of the original image. This functionality can be leveraged in themes that wish to include a set of default image styles created to work with the theme in question rather than having to rely on those provided by core.

Using responsive images means loading images that have been specifically sized for the screen based on screen width breakpoints. This practice makes websites load faster on mobile devices because image sizes are optimised for mobile devices. This is different than fluid images which are large images scaled with CSS.

The problem

Drupal does not create image styles upon node creation/update. You need to wait for someone to request the image (load the page) for it to generate/recreate itself. This can be a time consuming process and slow down the visitor experience. It also locks you into ‘the Drupal way’, which is against the integration of web services to Drupal.

The solution

To overcome this problem we've developed a custom module that forces the creation of different image styles upon node creation or update. This way images are ready to use in the template right afterwards. Image styles have been created using the admin UI at Configuration > Image Styles (admin/config/media/image-styles).

In our custom module a helper function that creates the images styles is called on hook_node_update and hook_node_insert on every image field attached to a content type.

if ( $node->hasField('field_image') ) {
  if ( $image_items = $node->getTranslation('en')->get('field_image')->getValue() ) { 
    $image_item = array_shift($image_items);
    _create_image_styles_helper($image_item['target_id']); 
  } 
}

The above code can be extended to various image fields, by adding multiple field keys. The helper function uses Drupal 8 class ImageStyle to create the new image uri and save the image and class File to retrieve initial image filepath.

Take a look at our web design and development services to see where we can help. 

Contact our team for more information on Drupal