HTML5
Web Workers
Run heavy computation on a background thread.
By EZ4Code Team
web-workersconcurrency
Code
// main.js
const worker = new Worker("worker.js");
worker.postMessage({ cmd: "sum", nums: [1, 2, 3, 4] });
worker.onmessage = e => {
console.log("Result:", e.data);
};
worker.onerror = e => console.error("Worker error:", e.message);
// worker.js
self.onmessage = function (e) {
const { cmd, nums } = e.data;
if (cmd === "sum") {
const total = nums.reduce((a, b) => a + b, 0);
self.postMessage(total);
}
};
// Workers cannot access the DOM, but can use fetch,
// setTimeout, and importScripts("lib.js")Explanation
Web Workers run scripts on a background thread, keeping heavy computation off the UI thread. The main thread and worker communicate asynchronously via postMessage and onmessage. Workers have no DOM access but can use fetch, timers, and importScripts.
More HTML5 Snippets
Semantic Elements
Structure a page with header, nav, main, article, and footer.
Form Input Types
Use native HTML5 input types, validation, and datalist.
Canvas Basics
Draw shapes, lines, and text on a 2D canvas.
Video & Audio
Embed media with multiple sources and control playback.
Local & Session Storage
Persist data in the browser with the Web Storage API.
Geolocation
Get the user's position and watch for changes.