Practical Guide to Using WebP Images in Web Projects
This article explains what WebP is, its performance benefits, common server‑side and client‑side integration methods, and shares a complete practical implementation—including image conversion tools, JavaScript detection, CSS mixins, and a Node.js monitoring script—to help developers adopt WebP efficiently in their front‑end workflows.
WebP, introduced by Google, can reduce image size by more than 25% compared with JPEG or PNG while maintaining visual quality, which significantly lowers page weight and improves load speed—especially important for mobile traffic where images often occupy over 80% of page size.
Two main integration approaches are discussed: (1) server‑side handling that checks the Accept: image/webp request header and serves WebP when supported, and (2) front‑end detection using JavaScript and cookies to decide which image format to request.
For the front‑end solution, the article provides a JavaScript snippet that tests WebP support with a tiny base64‑encoded WebP image, adds a .webps class to the html element, and stores a cookie ( webps=A ) for later use. The code must run before CSS is loaded:
;(function(doc) {
// add .webps class to html root
function addRootTag() {
doc.documentElement.className += " webps";
}
// check for existing cookie
if (!/(^|;\s?)webps=A/.test(document.cookie)) {
var image = new Image();
image.onload = function() {
// width == 1 means WebP is supported (base64 image is WebP)
if (image.width == 1) {
addRootTag();
document.cookie = "webps=A; max-age=31536000; domain=58.com";
}
};
// tiny transparent WebP image (base64)
image.src = 'data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAARBxAR/Q9ERP8DAABWUDggGAAAABQBAJ0BKgEAAQAAAP4AAA3AAP7mtQAAAA==';
} else {
addRootTag();
}
}(document));To serve WebP images in CSS, a SCSS mixin is introduced that outputs both the original and the WebP background‑image rules, leveraging the .webps class added by the script:
@mixin bg($url) {
background-image: url($url);
@at-root(with: all) .webps & {
background-image: url($url + '.webp');
}
}The same logic for Less is provided:
.mixin(@url) {
background-image: url(@url);
.webps & {
background-image: url('@{url}.webp');
}
}Because many background images are hosted on a CDN that does not generate WebP automatically, the article describes a Node.js monitoring script that watches an images folder, runs Google’s cwebp tool to create matching .webp files, and deletes them when the source image is removed. The script uses chokidar for file watching and child_process.exec to invoke the conversion command.
const process = require('child_process');
const fs = require('fs');
const chokidar = require('chokidar');
const log = console.log.bind(console);
const ignoreFiles = /(^\..+)|(.+[\/\\]\..+)|(.+?\.webp$)/; // ignore hidden and .webp files
let quality = 75; // default WebP quality
let imgDir = 'images'; // folder to watch
function getWebpImgName(path) {
return `${path}.webp`;
}
function getShellCmd(path) {
return `cwebp -q ${quality} ${path} -o ${getWebpImgName(path)}`;
}
var watcher = chokidar.watch(imgDir, {
ignored: path => ignoreFiles.test(path),
persistent: true
});
watcher.on('all', (event, path) => {
switch (event) {
case 'add':
case 'change':
generateWebpImg(path, status => {
log('生成图片' + getWebpImgName(path) + status);
});
break;
case 'unlink':
deleteWebpImg(getWebpImgName(path), status => {
log('删除图片' + getWebpImgName(path) + status);
});
break;
default:
break;
}
});
log('biubiubiu~~~ 监控已经启动');
function generateWebpImg(path, cb) {
process.exec(getShellCmd(path), err => {
if (err !== null) {
cb('失败');
log('请先运行cwebp -h命令检查cwebp是否安装ok。');
log(err);
} else {
cb('成功');
}
});
}
function deleteWebpImg(path, cb) {
fs.unlink(path, err => {
if (err) {
cb('失败');
log(err);
} else {
cb('成功');
}
});
}By combining these techniques—cwebp conversion, a Node.js watcher, front‑end detection, and CSS mixins—the authors successfully reduced the size of a production activity page, verified the results, and shared the full source on GitHub for others to adopt.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.