The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

Mojolicious::Plugin::LazyImage - Lazy load images

SYNOPSIS

  use Mojolicious::Lite;
  plugin "LazyImage";
  get "/" => {title => "Test"}, "index";
  app->start;

  __DATA__
  @@ index.html.ep
  <html>
    <head>
      <title><%= title %></title>
      <style>
        .lazy-image { opacity: 1; transition: opacity 0.3s; }
        .lazy-image[data-src] { opacity: 0; }
      </style>
    </head>
    <body>
      %= lazy_image '/images/whatever.jpg'
      %= javascript 'lazy_image'
    </body>
  </html>

DESCRIPTION

Mojolicious::Plugin::LazyImage is a Mojolicious plugin to lazy load images using JavaScript, but it also falls back to instantly load the images if the user has disabled JavaScript. The fallback is simply implemented by the IMG tag inside a NOSCRIPT tag.

For the users that have JavaScript enabled, the "lazy-image" JavaScript will observer the NOSCRIPT tags and replace them with the IMG tag inside once they get into the visible viewport.

The JavaScript require support for some recent web technologies, which might not be supported by your users. The resource below should add the required polyfills:

  <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Element.prototype.classList,IntersectionObserver,MutationObserver"></script>

HELPERS

lazy_image

This helper works just like the "image" in Mojolicious::Plugin::TagHelpers helper, but wraps the result inside a NOSCRIPT tag.

METHODS

javascript

  $text = Mojolicious::Plugin::LazyImage->javascript;

Returns the JavaScript source code. You can also fetch the source code directly using Mojo::Loader, but this is currently EXPERIMENTAL:

  Mojo::Loader::data_section("Mojolicious::Plugin::LazyImage", "/js/lazy-image.js")

register

Used to register this plugin into the Mojolicious application.

AUTHOR

Jan Henning Thorsen

COPYRIGHT AND LICENSE

This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.