2

We are using a field_image field across multiple content types. For the basic content type (only) we want to lazy load the images as such it requires the following format. How can this be done for just basic content type?

Current output:

<img src="some-url">

Desired output:

<img data-src="some-url">
  • 1
    You need to preprocess the image and modify the attributes based on the content type. – Kevin Dec 1 '17 at 20:10
3

You can do this by defining a "lazy load" image style and using it as the image display. This style does not have to do any resizing. It would just be a placeholder flag for a preprocess function like:

function my_theme_preprocess_image(&$variables) {
  if ( $variables['style_name'] == 'lazy_load') {
    $variables['attributes']['data-src'] = $variables['attributes']['src'];
    unset($variables['attributes']['src']);
  }
}

Nice thing is that you can use this style anywhere to get lazy loading images.

| improve this answer | |
  • +1 You stayed in the image preprocess and defined a unique identifier! That's the perfect solution! – leymannx Dec 1 '17 at 23:52
  • @CG Monroe, that works for me. I will however still do resizing along with the preprocess. – usernameabc Dec 4 '17 at 18:06
  • I have found with further testing that this solution does not work with Responsive Image module. Even though using Responsive Image module where different image styles are applied based on breakpoints, this does not work. The style_name is blank when i do a dpm($variables['style_name']). – usernameabc Dec 5 '17 at 20:50
  • @user2951257 - You added the info about using responsive images later. Which actually makes this a totally different question now. Better revert it as it was before, accept this answer and then ask a new question instead. "How to lazy-load responsive images" for example. – leymannx Dec 11 '17 at 23:22
  • 1
    @Clive this has been completed. Related question is added here. I could not find a way to link the two, so adding link here. drupal.stackexchange.com/questions/251951/… – usernameabc Dec 12 '17 at 6:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.