DEV Community

loading...

Laxy: Lazy initialization in JavaScript

Frederik 👨‍💻➡️🌐 Creemers
I'm never sure what to put in a bio. If there's anything you want to know, don't be afraid to ask!
・1 min read

GitHub logo jamestalmage / laxy

Proxies for lazy loading expensive objects

laxy Build Status codecov

Proxies for lazy loading expensive objects. Lazy + Proxy === Laxy

Install

$ npm install laxy

Usage

const laxy = require('laxy');
const proxy = laxy(generatorFn)(...argsToPass);
// generatorFn will only be called once, but not until you interact with the proxy in some way:
proxy();
proxy.foo;
Object.keys(proxy); // etc...
// Can be used as a lazy require
const _ = laxy(require)('lodash');

// lodash won't be loaded until you do something with it:
_.isNumber(3);

Basic API

laxy(generatorFn)(...argsToPass)

generatorFn

Type: fn

The function that should be called to generate the object being proxied. This function will be called lazily and only once.

...argsToPass

Type: anything

Any number of arguments may be provided and will be…

Laxy exports a single function that looks like this:

laxy(fn, ...args)

I think the easiest way to explain how it works, is with an example. Assume this is running in Node:

const laxy = require("laxy");
const fs = laxy(require, "fs");

Now, the fs module will be loaded, only when it is used. require is called with "fs" as the argument, the first time you try to use fs.

How it works

When you call laxy, it immediately returns an object. This object is a Proxy. The first time you use that object in any way that is supported by a Proxy handler, fn is called, and the object starts behaving exactly like the object returned by fn.

I used it to dramatically speed up the cold boot time of Google Cloud Functions for Firebase. Each function gets its own "container", but that container also includes the code for all the other functions, meaning I was loading dependancies for every function, not just the on in the current container. So I wrapped all dependancies in laxy, so they're only loaded the first time they're used.

Discussion (1)

Collapse
somedood profile image
Basti Ortiz (Some Dood)

Wow. This is actually really clever. I never thought of lazy-loading modules this way. Thanks for sharing!