ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Lazy image loading

October 24, 2012 8:17am

Subscribe [2]
  • #1 / Oct 24, 2012 8:17am

    rvinke

    1 posts

    Hi all,

    For a busy site I’m looking to ways to decrease server load and bandwith usage. One of the possible solutions is lazy loading of images. A often used Jquery-solution is the lazy load plugin (http://www.appelsiini.net/projects/lazyload).
    There is just one problem with this plugin: it requires to change the syntax of the img-tag. Normally it would be:

    path/to/image.jpg

    but that doesn’t result to a working lazy loading solution. The correct syntax for this plugin is shown on the link (something with data-original, the forum cleans out this tag)

    For my template images this is easy, but for the images in the entries (where the bulk of the heavy images is) it’s a bit more complicated. Does anyone have advice how to (automatically) rewrite/compose these new tags?

  • #2 / Oct 25, 2012 3:00pm

    rvinke

    1 posts

    Well, I’ve found a solution and I’ll post it here for people looking for a solution to the same problem.
    I’ve enabled php-parsing for the template where the entries are showed, and used the following php-code (altered a bit from https://github.com/jtai/wp-jquery-lazy-load):

    <?php
    function preg_replace_callback_img($matches) {
      // alter original img tag:
      //   - add empty class attribute if no existing class attribute
      //   - set src to placeholder image
      //   - add back original src attribute, but rename it to "data-original"
      if (!preg_match('/class\s*=\s*"/i', $matches[0])) {
        $class_attr = 'class="" ';
      }
    
      $replacement = $matches[1] . $class_attr . 'src="{site_url}assets/images/grey.gif" data-original' . substr($matches[2], 3) . $matches[3];
    
      // add "lazy" class to existing class attribute
      $replacement = preg_replace('/class\s*=\s*"/i', 'class="lazy ', $replacement);
    
      // add noscript fallback with original img tag inside
      //$replacement .= '<noscript>' . $matches[0] . '</noscript>';
      return $replacement;
    }
    
    echo preg_replace_callback('/(<\\\\s*img[^>]+)(src\\\\s*=\\\\s*"[^"]+")([^>]+>)/i', "preg_replace_callback_img", '{entry-content}');
    
    
    ?>

    For as far as I can see at the moment this works perfectly!

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases