My Goal:
Conditionally preload either the .webp version or the .jpg version of an image based on the version that will be served via the LiteSpeed cache plugin, not both.
Explanation:
I'm using the LightSpeed cache plugin on WordPress to automatically generate a webp version of images and serve them when possible using the 'Image WebP Replacement' feature.
Unfortunately, it does not always get it right, and sometimes serves the jpg version (especially if it's a background image) when it should be serving the webp version. Because of this, I cannot simply use a HTML preload tag for the webp image, because it may end up loading 2 images for some visitors.
I have tried many different variations of the snippet I am about to provide, but I have determined that I need it to check which version of the image the LiteSpeed cache plugin is going to serve and not just a simple check (such as if the browser supports webp or not). This is because if LiteSpeed cache determines it wants to serve the jpg version of an image, and my snippet determines that the webp version is the one that should be preloaded, then 2 images will end up being loaded for that user, where the one that is being preloaded is not even used by the browser.
Snippet:
<?php
// Set the URLs of the JPEG and WebP versions of the image
$jpgImageUrl = 'https://example.com/wp-content/uploads/image.jpg';
$webpImageUrl = 'https://example.com/wp-content/uploads/image.jpg.webp';
// Check if the LiteSpeed Cache plugin is serving the WebP version of the image
if (isset($_SERVER['HTTP_X_LSCACHE']) && strpos($_SERVER['HTTP_X_LSCACHE'], 'f=.webp') !== false) {
// If the LiteSpeed Cache plugin is serving the WebP version of the image, use the WebP version of the image for the preload
$backgroundImageUrl = $webpImageUrl;
} else {
// If the LiteSpeed Cache plugin is not serving the WebP version of the image, check if the LiteSpeed Cache plugin is serving the JPEG version of the image
if (isset($_SERVER['HTTP_X_LSCACHE']) && strpos($_SERVER['HTTP_X_LSCACHE'], 'f=.jpg') !== false) {
// If the LiteSpeed Cache plugin is serving the JPEG version of the image, use the JPEG version of the image for the preload
$backgroundImageUrl = $jpgImageUrl;
} else {
// If the LiteSpeed Cache plugin is not serving the JPEG or WebP version of the image, check if the browser supports WebP images and the WebP version of the image exists
if (imagetypes() & IMG_WEBP && file_exists($webpImageUrl)) {
// If WebP is supported and the WebP version of the image exists, use the WebP version of the image for the preload
$backgroundImageUrl = $webpImageUrl;
} else {
// If WebP is not supported or the WebP version of the image does not exist, use the JPEG version of the image for the preload
$backgroundImageUrl = $jpgImageUrl;
}
}
}
// Preload the image using the URL of the correct image format
echo '<link rel="preload" as="image" href="' . $backgroundImageUrl . '">';
EDIT: I forgot to mention that I want to avoid using JavaScript for this