I updated the snippet you can find in the laygridder's developper documentation to add lazysize="auto" for images.
I would like to enhance it further. But I don't want to spend too much time on it because it doesn't work everywhere in the layGridder.
Details below code
//img Markup with LQ source, data-src and auto-size
function get_respimg( $attid ) {
$full_src = wp_get_attachment_url( $attid );
$alt = get_post_meta($attid, '_wp_attachment_image_alt', true);
//ignore if gif||svg
if (substr($attr->sizes->full->url, -4) == '.gif' || '.svg' ) {
return '<img src="'.$element->sizes->full->url.'" alt="'.$alt.'">';
}
$lowQuality = wp_get_attachment_image_srcset($attid, 'thumbnail');
$srcset = wp_get_attachment_image_srcset($attid);
return '<img class="lazyload"
data-sizes="auto"
src="'.$lowQuality.'"
data-srcset="'.$srcset.'"
alt="'.$alt.'">';
}
}
//Lazysize layGridder
function lazyload_images_filter($markup, $element){
return '<div class="lg-placeholder" style="padding-bottom:'.($element->h/$element->w*100).'%;">'.get_respimg($element->attid).'</div>';
}
add_filter( 'lg_frontend_img', 'lazyload_images_filter', 10, 2 );
function enqueue_lazysizes_js(){
wp_enqueue_script( 'lazysizes-js', "https://cdnjs.cloudflare.com/ajax/libs/lazysizes/2.0.6/lazysizes.min.js");
}
add_action( 'wp_enqueue_scripts', 'enqueue_lazysizes_js' );
What it does and why:
- it includes data-size="auto" to always serve you the best fitting image and decrease load time
- I also included a lowquality initial image source to enhance percieved loading
(my thumbnails are 28px wide. needs a separate css blur until it is lazyloaded) - I splitted the function into "get_respimg()" and lg_frontend_img filter to reuse it in other places.
What it can't do
- work on every images in the gridder
It's a start :
It only works on images added as elements in the gridder.
There is at least two other ways to include images in the gridder : background-images and post_thumbnails.
post_thumbnail has it's own filter so I could add support for this but row background-images doesn't have a filter.
So I splitted created the resp_img() function separately in hope that we would either get a filter for background-images or a filter for all images. (this way we could also develop custom elements using that filter).
Idealy I could make it into a little laygridder lazysizes advanced plug-in with better markup/polyfills/compatibility and opt-ins to add blur-effects, config wordpress image sizes, etc.
But for now i'm stopping there until there is support for background-images.