Progressive Enhancement Audit Framework (PEAF)
As Sherlock Holmes might deduce from a tangle of clues, progressive enhancement is the art of building resilient web experiences: start with a robust HTML/CSS core that functions universally (even without JavaScript), then layer enhancements gracefully. Degradations occur when JavaScript becomes a crutch—blocking core functionality if disabled or failed.
I've engineered PEAF, a modular, automated audit framework to:
- Document JS-dependent features (e.g., dynamic forms, lazy-loaded content).
- Detect degradations (e.g., inaccessible navigation, broken interactions).
- Orchestrate fixes (prioritized remediation plans with code snippets).
PEAF uses Node.js, Playwright for browser automation, and Cheerio for static analysis. It's extensible, runs locally or in CI/CD, and outputs an interactive HTML report.
Prerequisites
npm init -y
npm install playwright cheerio html-compare puppeteer-core lighthouse axios fs-extra
npx playwright install # Browsers: Chromium, Firefox, WebKit
Core Audit Pipeline
PEAF orchestrates four phases: Scan, Compare, Analyze, Remediate. Run via CLI: node audit.js --url=https://example.com.
1. Scan Phase: Document JS-Dependent Features
- With JS: Full crawl, capture DOM snapshots, interactions, performance.
- Without JS: Replay crawl with JS disabled, capture static HTML.
- Static Analysis: Parse source for JS hooks (e.g.,
onclick, addEventListener).
Key Artifacts:
- Screenshots (full-page, elements).
- HAR files (network requests).
- Feature inventory: Maps URLs to JS-reliant elements (e.g., "Hero carousel hidden without JS").
Script: scanner.js
const { chromium, devices } = require('playwright');
const fs = require('fs-extra');
const path = require('path');
async function scanSite(url, outputDir, jsEnabled = true) {
const browser = await chromium.launch();
const context = await browser.newContext({
...devices['Desktop Chrome'],
javaScriptEnabled: jsEnabled,
viewport: { width: 1280, height: 720 }
});
const page = await context.newPage();
// Crawl: Intercept navigations, capture snapshots
const snapshots = [];
page.on('domcontentloaded', async () => {
const title = await page.title();
const html = await page.content();
const screenshot = await page.screenshot({ fullPage: true });
snapshots.push({
url: page.url(),
title,
html: html.replace(/<script.*?<\/script>/gis, ''), // Strip JS for diff
screenshot: `data:image/png;base64,${screenshot.toString('base64')}`,
timestamp: new Date().toISOString()
});
});
await page.goto(url, { waitUntil: 'networkidle' });
// Simulate interactions: Click links, forms (customize per site)
await page.click('a[href]', { timeout: 5000 }).catch(() => {});
await page.waitForTimeout(2000);
await fs.outputJson(path.join(outputDir, `scan-${jsEnabled ? 'js' : 'nojs'}.json`), snapshots);
await browser.close();
}
// Usage
await scanSite('https://example.com', './audits/full');
await scanSite('https://example.com', './audits/nojs', false);
Output Example (from scan-js.json):
[
{
"url": "https://example.com/",
"features": ["Dynamic menu (via JS toggle)", "Lazy images (IntersectionObserver)"],
"jsHooks": ["document.querySelector('.menu').addEventListener('click', ... )"]
}
]
2. Compare Phase: Detect Degradations
- Pixel-diff screenshots.
- DOM diff: Structural changes (e.g., missing
<noscript> fallbacks).
- Functionality checks: Forms submit? Links navigate?
- Metrics: Load time delta, accessibility score drop.
Script: comparator.js
const fs = require('fs-extra');
const { diff } = require('html-compare'); // npm i html-compare
const pixelmatch = require('pixelmatch'); // npm i pixelmatch pngjs
const PNG = require('pngjs').PNG;
async function detectDegradations(jsScan, noJsScan, reportDir) {
const degradations = [];
for (let i = 0; i < Math.min(jsScan.length, noJsScan.length); i++) {
const jsSnap = jsScan[i], noJsSnap = noJsScan[i];
// HTML diff
const htmlDiff = diff(jsSnap.html, noJsSnap.html);
if (htmlDiff.added.length > 5 || htmlDiff.removed.length > 5) {
degradations.push({
url: jsSnap.url,
type: 'DOM Collapse',
severity: 'HIGH',
diff: htmlDiff
});
}
// Screenshot diff
const jsImg = PNG.sync.read(Buffer.from(jsSnap.screenshot, 'base64'));
const noJsImg = PNG.sync.read(Buffer.from(noJsSnap.screenshot, 'base64'));
const diffImg = new PNG({ width: jsImg.width, height: jsImg.height });
const numDiffPixels = pixelmatch(jsImg.data, noJsImg.data, diffImg.data, jsImg.width, jsImg.height, { threshold: 0.1 });
if (numDiffPixels > 10000) { // Threshold: ~5% diff
degradations.push({
url: jsSnap.url,
type: 'Visual Regression',
severity: 'MEDIUM',
diffPixels: numDiffPixels
});
}
}
await fs.outputJson(path.join(reportDir, 'degradations.json'), degradations);
}
3. Analyze Phase: Lighthouse + Custom Checks
Integrate Lighthouse for perf/SEO audits (JS vs no-JS).
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
async function runLighthouse(url, jsEnabled) {
const chrome = await chromeLauncher.launch({ chromeFlags: [`--disable-javascript=${!jsEnabled}`] });
const options = { logLevel: 'info', output: 'json', port: chrome.port };
const result = await lighthouse(url, options);
await chrome.kill();
return result.lhr;
}
- Degradation Signals: Core Web Vitals drop >20%, TTI infinite without JS.
4. Remediate Phase: Orchestrate Fixes
- Prioritize: HIGH (core nav/forms broken), MEDIUM (UX polish missing), LOW (perf enhancements).
- Auto-Fix Suggestions: Generate PR-ready patches.
- Refactor Patterns:
| Degradation | Fix Template |
|---|
| Hidden nav | <noscript><ul class="nojs-menu">{links}</ul></noscript> + CSS .nojs-menu { display: block; } |
| Form fails | Server-side fallback + <noscript><input type="submit" value="Submit"></noscript> |
| Lazy images | <noscript><img src="full.jpg" alt="..."></noscript> inside lazy <img loading="lazy"> |
| SPA routing | <a href="/page"> with e.preventDefault() in JS |
Script: remediator.js
function generateFixes(degradations) {
return degradations.map(deg => ({
...deg,
fixes: [
'Add <noscript> fallback for ' + deg.type,
'Code: ```html\n<noscript>...</noscript>\n```',
'Test: Re-run audit post-fix'
],
priority: deg.severity === 'HIGH' ? 1 : 2
})).sort((a, b) => a.priority - b.priority);
}
Full CLI Orchestrator: audit.js
// Combine all: node audit.js --url=https://yoursite.com --out=./report
// Generates index.html with diffs, tables, fix buttons.
Sample Report Output (Interactive HTML):
| URL | Feature | Degradation | Severity | Fix |
|---|
| /home | Search form | No submit without JS | HIGH | Add <noscript> button |
| /products | Image carousel | Static list (good!) | NONE | N/A |
Running the Audit
mkdir audits && node audit.js --url=https://example.com
- Open
report/index.html.
- CI Integration: GitHub Actions YAML snippet available on request.
Extensions
- Multi-page Crawl: Integrate
playwright-crawler.
- Accessibility: Pipe to Axe-core.
- Real-user Metrics: Web Vitals API.
- Edge Cases: Low-bandwidth, ad-blockers.
This framework uncovers hidden dependencies like a web of deceit, ensuring your site thrives in any environment. Questions or site-specific tweaks? The game is afoot.