Web Worker driven Classes and methods

Andrea Giammarchi
May 22, 2018 · 4 min read

He dropped 95% of a bundle size with a simple trick

self.addEventListener('message', event => {
switch(event.data.cmd) {
case 'initializeApp': ...
case 'firestore.col.add': ...
case 'firestore.col.onSnapshot': ...
}
});

workway: a general purpose Web Worker exporter

a @jonathan_klok walkway picture from @unsplash
// file /worker.js
importScripts('https://unpkg.com/workway/worker.js');
// import anything else needed and initialize firestorm// expose remotely the following namespace
// either as object or Promise that will resolve one
workway({
utils: {
random: (size = 8) => String.fromCharCode(
...crypto.getRandomValues(new Uint8Array(size))
)
},
app: {
User: class User {
constructor() {
this.uid = firebase.auth().currentUser.uid;
}
getName() {
return firebase.database()
.ref('/users/' + this.uid)
.once('value')
.then(snapshot => ((
snapshot.val() && snapshot.val().username
) || 'Anonymous'));
}
}
}
});
// generic message listeners (addEventListener works too)
self.onmessage = event => console.log(event.data);
// file /bundle.js for the main thread
workway('/worker.js').then(async ({worker, namespace}) => {
const user = new namespace.app.User;
user.getName().then(name => {
worker.postMessage(`Thanks from ${name}!`);
});
const rand = await namespace.utils.random(16);
console.log(rand);
});

Offload as much as possible for a cost of 0.5K !

Key features

As Summary

Andrea Giammarchi

Written by

Web, Mobile, IoT, and all JS things since 00's. Formerly JS engineer at @nokia, @facebook, @twitter.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade