This is a comprehensive request to create a progressive image loading system using Blurhash. Let me break down what's needed:
Blurhash Library : Use the blurhash library to encode/decode images
Server Component : Generate blurhash strings for images
Client Component : Web component that handles lazy loading with blur placeholder
Progressive Enhancement : Show blur, then cross-fade to full image
Reusable Web Component : Package it as a custom element
Let me create a complete solution:
Key Components:
1. Server-side (Node.js/Express example)
Generate blurhash from image
Return hash with metadata
2. Client-side Web Component
Decode blurhash to canvas
Show as placeholder
Lazy load full image
Smooth cross-fade transition
3. Styling
CSS for transitions
Responsive container
Let me write comprehensive code with examples:
javascript Copy code
// Server: blurhash-generator.js
import blurhash from 'blurhash';
import sharp from 'sharp';
import fs from 'fs';
export async function generateBlurhash(imagePath, size = 100) {
try {
// Read image and convert to UInt8Clamped array
const image = await sharp(imagePath)
.resize(size, size, { fit: 'cover' })
.raw()
.toBuffer({ resolveWithObject: true });
const { data, info } = image;
const pixels = new Uint8ClampedArray(data);
// Encode blurhash
const hash = blurhash.encode(pixels, info.width, info.height, 4, 3);
return hash;
} catch (error) {
console.error('Error generating blurhash:', error);
throw error;
}
}
Now I need to build out the full production-ready implementation with the complete web component, styling, utilities, and practical examples that tie everything together.
Progressive Image Loading with Blurhash
I'll create a complete, production-ready progressive image loading system using Blurhash. This includes server-side hash generation, a reusable web component, and smooth cross-fade transitions.
1. Server-Side Hash Generation
javascript Copy code
// server/blurhash-generator.js
import sharp from 'sharp';
import * as BlurHash from 'blurhash';
import fs from 'fs/promises';
import path from 'path';
/**
* Generate blurhash from image file
*/
export async function generateBlurhash(
imagePath,
componentX = 4,
componentY = 3,
resizeSize = 100
) {
try {
const image = await sharp(imagePath)
.resize(resizeSize, resizeSize, { fit: 'cover' })
.raw()
.toBuffer({ resolveWithObject: true });
const { data, info } = image;
const pixels = new Uint8ClampedArray(data);
const hash = BlurHash.encode(
pixels,
info.width,
info.height,
componentX,
componentY
);
return hash;
} catch (error) {
console.error('Error generating blurhash:', error);
throw error;
}
}
/**
* Process and generate metadata for images
*/
export async function processImageMetadata(inputPath, outputPath) {
try {
const metadata = await sharp(inputPath).metadata();
const blurhash = await generateBlurhash(inputPath);
const imageMetadata = {
blurhash,
width: metadata.width,
height: metadata.height,
aspectRatio: metadata.width / metadata.height,
format: metadata.format,
size: (await fs.stat(inputPath)).size,
};
await fs.writeFile(
outputPath,
JSON.stringify(imageMetadata, null, 2)
);
return imageMetadata;
} catch (error) {
console.error('Error processing image metadata:', error);
throw error;
}
}
/**
* Batch process multiple images
*/
export async function batchProcessImages(imageDir, outputDir) {
const results = {};
try {
const files = await fs.readdir(imageDir);
const imageFiles = files.filter(file =>
/\.(jpg|jpeg|png|webp)$/i.test(file)
);
for (const file of imageFiles) {
const inputPath = path.join(imageDir, file);
const outputPath = path.join(outputDir, `${file}.json`);
results[file] = await processImageMetadata(inputPath, outputPath);
console.log(`✓ Processed ${file}`);
}
return results;
} catch (error) {
console.error('Error batch processing images:', error);
throw error;
}
}
2. Express API Endpoint
javascript Copy code
// server/routes/images.js
import express from 'express';
import multer from 'multer';
import path from 'path';
import { generateBlurhash, processImageMetadata } from '../blurhash-generator.js';
const router = express.Router();
const upload = multer({ dest: 'uploads/temp/' });
/**
* GET /api/images/blurhash/:filename
* Get blurhash for an image
*/
router.get('/blurhash/:filename', async (req, res) => {
try {
const imagePath = path.join(process.cwd(), 'public/images', req.params.filename);
const blurhash = await generateBlurhash(imagePath);
res.json({
blurhash,
filename: req.params.filename
});
} catch (error) {
res.status(400).json({ error: error.message });
}
});
/**
* POST /api/images/metadata
* Generate metadata for uploaded image
*/
router.post('/metadata', upload.single('image'), async (req, res) => {
try {
if (!req.file) {
return res.status(400).json({ error: 'No image provided' });
}
const metadata = await processImageMetadata(
req.file.path,
path.join(process.cwd(), 'public/metadata', `${req.file.filename}.json`)
);
res.json({
success: true,
metadata,
filename: req.file.filename
});
} catch (error) {
res.status(400).json({ error: error.message });
}
});
/**
* Serve pre-generated metadata
*/
router.get('/metadata/:filename', async (req, res) => {
try {
const metadataPath = path.join(
process.cwd(),
'public/metadata',
`${req.params.filename}.json`
);
const metadata = JSON.parse(
await require('fs').promises.readFile(metadataPath, 'utf-8')
);
res.json(metadata);
} catch (error) {
res.status(404).json({ error: 'Metadata not found' });
}
});
export default router;
3. Reusable Web Component
4. Advanced Features & Plugins
javascript Copy code
// client/lazy-img-advanced.js
import LazyImg from './lazy-img.js';
/**
* Extended LazyImg with srcset and responsive loading
*/
export class LazyImgAdvanced extends LazyImg {
static get observedAttributes() {
return [
'src',
'srcset',
'sizes',
'blurhash',
'blurhashes',
'alt',
'width',
'height',
'ratio',
'loading-priority'
];
}
connectedCallback() {
super.connectedCallback();
this.currentSize = this.getCurrentSize();
}
render() {
super.render();
this.setupSrcset();
}
setupSrcset() {
const srcset = this.getAttribute('srcset');
if (srcset) {
this.img.setAttribute('srcset', srcset);
const sizes = this.getAttribute('sizes');
if (sizes) {
this.img.setAttribute('sizes', sizes);
}
}
}
/**
* Handle multiple blurhashes for different sizes
*/
renderOptimalBlurhash() {
const blurhashes = this.getAttribute('blurhashes');
if (!blurhashes) return;
try {
const hashes = JSON.parse(blurhashes);
const size = this.getCurrentSize();
const blurhash = hashes[size] || hashes.default || Object.values(hashes)[0];
if (blurhash) {
this.renderBlurHash(blurhash);
}
} catch (error) {
console.error('Error parsing blurhashes:', error);
}
}
getCurrentSize() {
const width = window.innerWidth;
if (width < 640) return 'sm';
if (width < 1024) return 'md';
if (width < 1536) return 'lg';
return 'xl';
}
/**
* Priority loading - load immediately if priority is high
*/
setupIntersectionObserver() {
const priority = this.getAttribute('loading-priority');
if (priority === 'high') {
this.loadImage();
return;
}
super.setupIntersectionObserver();
}
}
customElements.define('lazy-img-advanced', LazyImgAdvanced);
/**
* Utility: Generate HTML with metadata
*/
export function createLazyImgHTML(imageData, options = {}) {
const {
responsive = false,
sizes = '(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw',
priority = 'normal',
ratio = '16 / 9'
} = options;
const attributes = [
`src="${imageData.src}"`,
`alt="${imageData.alt || ''}"`,
`blurhash="${imageData.blurhash}"`,
`ratio="${ratio}"`,
`loading-priority="${priority}"`,
];
if (responsive && imageData.srcset) {
attributes.push(`srcset="${imageData.srcset}"`);
attributes.push(`sizes="${sizes}"`);
}
if (imageData.blurhashes && typeof imageData.blurhashes === 'object') {
attributes.push(`blurhashes='${JSON.stringify(imageData.blurhashes)}'`);
}
return `<lazy-img-advanced ${attributes.join(' ')}></lazy-img-advanced>`;
}
5. HTML Example
6. CLI Tool for Batch Processing
bash Copy code
#!/usr/bin/env node
// bin/blurhash-cli.js
import fs from 'fs/promises';
import path from 'path';
import yargs from 'yargs';
import { hideBin } from 'yargs/helpers';
import chalk from 'chalk';
import ora from 'ora';
import { generateBlurhash, batchProcessImages } from '../server/blurhash-generator.js';
const argv = yargs(hideBin(process.argv))
.command('generate <image>', 'Generate blurhash for a single image', (yargs) => {
return yargs.positional('image', {
describe: 'Path to image file',
type: 'string'
});
})
.command('batch <input-dir> <output-dir>', 'Process all images in a directory', (yargs) => {
return yargs
.positional('input-dir', { describe: 'Input directory', type: 'string' })
.positional('output-dir', { describe: 'Output directory', type: 'string' });
})
.option('components-x', {
alias: 'cx',
describe: 'Components X',
default: 4,
type: 'number'
})
.option('components-y', {
alias: 'cy',
describe: 'Components Y',
default: 3,
type: 'number'
})
.argv;
async function handleGenerate() {
const spinner = ora('Generating blurhash...').start();
try {
const hash = await generateBlurhash(
argv.image,
argv.componentsX,
argv.componentsY
);
spinner.succeed(chalk.green('Blurhash generated!'));
console.log(chalk.cyan('\nBlurhash: ') + chalk.bold(hash));
} catch (error) {
spinner.fail(chalk.red('Error: ' + error.message));
}
}
async function handleBatch() {
const spinner = ora('Processing images...').start();
try {
await fs.mkdir(argv.outputDir, { recursive: true });
const results = await batchProcessImages(argv.inputDir, argv.outputDir);
spinner.succeed(chalk.green(`Successfully processed ${Object.keys(results).length} images!`));
console.log(chalk.cyan('\nResults:'));
Object.entries(results).forEach(([file, data]) => {
console.log(`\n ${chalk.bold(file)}`);
console.log(` ${chalk.dim('Hash: ')}${data.blurhash}`);
console.log(` ${chalk.dim('Size: ')}${data.width}x${data.height}`);
});
} catch (error) {
spinner.fail(chalk.red('Error: ' + error.message));
}
}
// Main
const command = argv._[0];
if (command === 'generate') {
handleGenerate();
} else if (command === 'batch') {
handleBatch();
} else {
console.log(chalk.yellow('Please specify a command: generate or batch'));
}
7. Testing & Performance
javascript Copy code
// tests/lazy-img.test.js
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import LazyImg from '../client/lazy-img.js';
describe('LazyImg Component', () => {
let element;
beforeEach(() => {
element = document.createElement('lazy-img');
element.setAttribute('src', '/test-image.jpg');
element.setAttribute('blurhash', 'UeKUpqxuo2NLxvFQqS7NcD4qIllR');
element.setAttribute('alt', 'Test Image');
document.body.appendChild(element);
});
afterEach(() => {
document.body.removeChild(element);
});
it('renders shadow DOM', () => {
expect(element.shadowRoot).toBeTruthy();
expect(element.shadowRoot.querySelector('canvas')).toBeTruthy();
expect(element.shadowRoot.querySelector('img')).toBeTruthy();
});
it('decodes blurhash to canvas', (done) => {
setTimeout(() => {
const canvas = element.shadowRoot.querySelector('canvas');
expect(canvas.width).toBe(32);
expect(canvas.height).toBe(32);
done();
}, 100);
});
it('loads image on intersection', (done) => {
element.addEventListener('imageloaded', () => {
const img = element.shadowRoot.querySelector('img');
expect(img.classList.contains('loaded')).toBe(true);
done();
});
element.loadImage();
});
it('handles image load errors', (done) => {
element.setAttribute('src', '/nonexistent-image.jpg');
element.addEventListener('imageerror', () => {
done();
});
element.loadImage();
});
it('provides reload functionality', () => {
expect(element.reload).toBeTruthy();
expect(typeof element.reload).toBe('function');
});
});
// Performance benchmark
import { performance } from 'perf_hooks';
async function benchmarkBlurhashDecoding() {
const hashes = [
'UeKUpqxuo2NLxvFQqS7NcD4qIllR',
'L6Pj0^jE.AyE_3t757oJodS4mejt',
'UnQf83Rj^j}s=.W;IVoL00X9V@oL'
];
console.log('Blurhash Decoding Performance:');
hashes.forEach(hash => {
const start = performance.now();
for (let i = 0; i < 1000; i++) {
BlurHash.decode(hash, 32, 32);
}
const end = performance.now();
console.log(` Hash ${hash.slice(0, 10)}... : ${((end - start) / 1000).toFixed(3)}ms per decode`);
});
}
8. Package.json
json Copy code
{
"name": "progressive-blurhash-loader",
"version": "1.0.0",
"type": "module",
"description": "Progressive image loading with Blurhash",
"scripts": {
"start": "node server/index.js",
"dev": "nodemon server/index.js",
"test": "vitest",
"blurhash": "node bin/blurhash-cli.js"
},
"dependencies": {
"express": "^4.18.2",
"blurhash": "^2.0.5",
"sharp": "^0.32.0",
"multer": "^1.4.5",
"dotenv": "^16.0.3"
},
"devDependencies": {
"vitest": "^0.34.0",
"nodemon": "^3.0.1",
"yargs": "^17.7.2",
"chalk": "^5.3.0",
"ora": "^6.1.0"
}
}
Key Features:
✅ Blurhash Encoding/Decoding - Fast, efficient image placeholders
✅ Progressive Loading - Show blur → load full image → cross-fade
✅ Lazy Loading - Intersection Observer with margin
✅ Responsive - Works with srcset and sizes attributes
✅ Error Handling - Graceful fallbacks and error events
✅ Web Component - Reusable, framework-agnostic
✅ Accessibility - ARIA labels, alt text, reduced motion support
✅ Performance - Minimal JS, efficient decoding
✅ CLI Tool - Batch hash generation
✅ Analytics - Event tracking and performance metrics
This solution provides production-ready progressive image loading!