A simple plugin to enable lazy loading for all images using WordPress image functions.
How can I change the default placeholder color?
As of 2.0.0, Images now load as a transparent gif, which should remove the need to add custom image colors, and make it work in more situations automatically.
Fade in images as they load
With the new lazy load library, a few helper CSS classes are included by default. The full documentation can be found here, but the gist of it [pulled from the github repo] is as follows:
/* fade image in after load */
.lazyload,
.lazyloading {
opacity: 0;
}
.lazyloaded {
opacity: 1;
transition: opacity 300ms;
}
Fallback
As of 1.4.0, the plugin also adds support for a noscript
fallback so the images will appear in browsers that might have Javascript disabled.
To take full advantage of this, the plugin provides a fully automatic solution using the following filter to your functions.php
, add_filter( 'lazy_load_enable_fallback', '__return_true' )
. This method will automatically handle all of the below instructions. If you’re developing a custom theme you might want to include the following instructions manually, in that case you can use add_filter( 'lazy_load_enable_noscript', '__return_true' )
to only add the <noscript>
tags and leave the styles, javascript, and body classes untouched.
NOTE: This fallback only works on the images that are replaced inside the body of the pages, and those generated by using the_post_thumbnail
.
Add the following CSS:
.no-js .lazyload.lazy-fallback {
display: none;
}
Add the following JS inside as close to the opening body
tag as possible:
<script type="text/javascript">
var body = document.getElementsByTagName('body')[0];
if (body != undefined) {
body.setAttribute('class', body.getAttribute('class').replace('no-js', ''));
}
</script>
And append this snippet to your functions.php:
add_filter( 'body_class', function ( $classes, $class ) {
if ( ! in_array( 'no-js', $classes ) ) {
$classes[] = 'no-js';
}
return $classes;
}, 10, 2 );