苹果系列的浏览器不支持webp格式图片怎么办
在使用Webp格式的图片提高网站的加载速度中讲到webp格式的图片对于提高网站加载速度,降低宽带使用很有帮助,哆麦CMS可以帮助把所有图片都转化为webp格式。目前大多数浏览器都支持webp图片,但是有一个重要的问题是,目前苹果系列下的原装浏览器safari目前不支持展示webp格式的图片,虽然safari的浏览量占比很低,但是使用这类设备的用户往往具有更好的转化率,这里提供一种让safari浏览器也支持webp浏览的方法。
一,在主题的functions.php中加入以下代码:
function webp2jpg(){
$image = ABSPATH.str_replace('https://你的网站域名/', '', $_REQUEST['f']);
if(!file_exists($image) || !function_exists('imagecreatefromwebp') || substr($image, -5) != '.webp'){
status_header(500);
die;
}
header("Content-Type:image/jpeg");
header("Cache-Control: public,max-age=864000");
$webp = imagecreatefromwebp($image);
imagejpeg($webp);
imagedestroy($webp);
}
add_action('ajax_web2jpg', 'web2jpg');二,把以下JavaScript代码添加到页面中:
(function(){
function supportwebp() {
var elem = document.createElement('canvas');
if (!!(elem.getContext && elem.getContext('2d'))) {
return elem.toDataURL('image/webp').indexOf('data:image/webp') == 0;
}
return false;
}
if(supportwebp()) return;
var images = document.querySelectorAll('img');
for(var i in images){
var originsrc = images[i].src;
if(originsrc && originsrc.substr(-5) == '.webp' && ( originsrc.substr(0, 24) == 'https://你的网站域名/' || originsrc.substr(0,1) == '/')){
images[i].src = 'https://你的网站域名/dm-ajax.php?action=webp2jpg&f='+encodeURIComponent(originsrc);
}
}
})();如果网站使用的不是https协议,把上述段代码的https替换为http即可。

评论列表