基于LiteSpeed缓存插件的PHP有条件预加载图片



My Goal:
根据LiteSpeed缓存插件提供的版本,有条件地预加载。webp版本或。jpg版本的图片,而不是同时预加载。

解释:
我正在使用WordPress上的LightSpeed缓存插件来自动生成图像的webp版本,并在可能的情况下使用'Image webp Replacement'功能为它们提供服务。

不幸的是,它并不总是正确的,有时当它应该提供webp版本时,它会提供jpg版本(特别是如果它是背景图像)。因此,我不能简单地为webp图像使用HTML预加载标签,因为它可能最终为一些访问者加载2张图像。

我已经尝试了我即将提供的片段的许多不同的变体,但我已经确定我需要它来检查LiteSpeed缓存插件将要服务的图像的哪个版本,而不仅仅是一个简单的检查(例如浏览器是否支持webp)。这是因为如果litesspeed缓存确定它想要提供图像的jpg版本,并且我的代码片段确定webp版本应该被预加载,那么最终将为该用户加载2张图像,其中正在预加载的图像甚至不被浏览器使用。

片段:

<?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 . '">';

编辑:我忘了说,我要避免对这个

使用JavaScript

不完全是你的问题的答案,但一个解决办法来获得webp,不是wordpress的方式虽然,但它应该工作

<IfModule LiteSpeed>
RewriteCond %{HTTP_ACCEPT} "image/webp"
RewriteCond %{REQUEST_FILENAME}.webp -f
RewriteRule ^(.*).(jpg|jpeg|png|gif) $1.$2.webp [T=image/webp,L]
</IfModule>

这个重写规则将检查浏览器是否支持webp,如果something.jpg.webp存在,如果存在,强制加载something.jpg.webp,否则回退到默认的something.jpg

URI将保持为something.jpg,但格式/内容将加载为something.jpg.webp

最新更新