Lazy Loading Implementation in JavaScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Lazy Loading runs in O(1) time and O(1) space, in JavaScript as in every other language.
- ✓There is no lazy type in the language, only three primitives you compose. Accessor properties, declared with get in a class or object literal or installed through Object.defineProperty, give you the interception point.
- ✓Memoise the promise, never the resolved value. Two callers hitting a cold cache before the network settles must share one in-flight request, and only a stored promise gives you that.
- ✓The JavaScript trap: The self-replacing getter is the classic shape, and the classic shape breaks when the getter lives on a prototype.
- ✓Both halves of the pattern move an object between hidden classes. Defining an own accessor in the constructor is one shape transition, redefining it as a data property is a second, so a call site that reads .spans on a cold instance and then a warm one has seen two shapes and its inline cache goes polymorphic.
What Lazy Loading actually is
Lazy Loading in JavaScript: what you actually reach for
JavaScript implementation
// Two lazies that behave differently: a sync own-property install,
// and a memoised dynamic import for the heavy highlighter grammar.
const GRAMMAR_KEYS = ["kw", "str", "num", "cmt"];
export class Highlighter {
constructor(source) {
this.source = source;
// Install the accessor as an OWN property. A getter on the prototype
// cannot cache with this.x = v: the prototype accessor has no setter,
// and class bodies are strict, so that assignment throws TypeError.
Object.defineProperty(this, "spans", {
configurable: true,
get() {
const built = GRAMMAR_KEYS.map((k) => [k, scan(this.source, k)]);
// Replace the accessor with a plain data property: the second
// read is an ordinary slot lookup, not a call into the getter.
Object.defineProperty(this, "spans", {
value: built, writable: false, configurable: false,
});
return built;
},
});
}
}
function scan(src, kind) {
return src.length === 0 ? [] : [{ kind, at: 0 }];
}
let rendererPromise = null;
export function renderer() {
// Memoise the PROMISE, not the module: concurrent callers before the
// network settles must share one in-flight request, not start N.
if (rendererPromise === null) {
rendererPromise = import("./markdown-renderer.mjs").catch((err) => {
rendererPromise = null; // do not cache a rejection forever
throw err;
});
}
return rendererPromise;
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe JavaScript-specific trap
Performance in JavaScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which JavaScript type or library should I use for Lazy Loading?
There is no lazy type in the language, only three primitives you compose. Accessor properties, declared with get in a class or object literal or installed through Object.defineProperty, give you the interception point. The module registry supplies free memoisation: a module body evaluates once per resolved URL and every later import receives the identical namespace object. Dynamic import() returns a promise for that namespace and is the only standard way to defer fetching the code itself. WeakMap covers per-object side caches for objects you cannot add a property to.
What is the most common JavaScript mistake when implementing Lazy Loading?
The self-replacing getter is the classic shape, and the classic shape breaks when the getter lives on a prototype. Writing this.spans = built inside a prototype accessor performs an ordinary Set, which walks the prototype chain, finds an accessor whose [[Set]] is undefined, and fails. Class bodies and modules are always strict, so that failure surfaces as TypeError: Cannot set property spans of #<Highlighter> which has only a getter. In a sloppy-mode script it is worse: the write is discarded in silence, no own property appears, and the getter re-runs on every access forever while looking cached. Install the accessor as an own property instead.
How does Lazy Loading actually perform in JavaScript?
Both halves of the pattern move an object between hidden classes. Defining an own accessor in the constructor is one shape transition, redefining it as a data property is a second, so a call site that reads .spans on a cold instance and then a warm one has seen two shapes and its inline cache goes polymorphic. For dynamic import() the constants are dominated by the network: one request, a parse, and a graph walk of the chunk's own dependencies, all against a registry keyed on the resolved URL, so two specifiers that resolve to the same URL share a single evaluation. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for Replit, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.