Mojolicious::Plugin::LazyImage - Lazy load images
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>
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>
This helper works just like the "image" in Mojolicious::Plugin::TagHelpers helper, but wraps the result inside a NOSCRIPT tag.
$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")
Used to register this plugin into the Mojolicious application.
Jan Henning Thorsen
This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.
To install Mojolicious::Plugin::LazyImage, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Mojolicious::Plugin::LazyImage
CPAN shell
perl -MCPAN -e shell install Mojolicious::Plugin::LazyImage
For more information on module installation, please visit the detailed CPAN module installation guide.