Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Lazy Loading Implementation in JavaScript

11 min readbeginner
Website QA and SEO audits

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 defers the cost of building something until the first caller actually needs it: a parsed rule table, a compiled pattern, a database handle, or a megabyte of code that most sessions never execute. The mechanics look trivial. Check whether a slot is empty, fill it, hand it back. That apparent simplicity is exactly why it stays a durable source of subtle bugs. Two threads can arrive at the empty slot together. A memory model can let one of them publish the reference before the object's own field writes become visible to the other, which is what turns naive double-checked locking into a correctness defect rather than a style preference. A factory that throws leaves a third state, neither empty nor filled, and every runtime answers it differently: retry on the next call, cache the failure permanently, or quietly mark the work done and hand out a zero value. Deferring also moves work rather than deleting it, so one unlucky request pays a latency spike the next thousand do not. The eight implementations here disagree at nearly every level. Four hand you a dedicated once-token in the standard library, and hand-rolling your own there is a review failure. Two make global laziness a language guarantee you cannot switch off, so the whole singleton pattern collapses into one keyword. One erases its lazy declarations entirely at compile time, leaving the emitted behaviour hostage to a compiler flag most teams set once and never read again. One treats a failed initialisation as permanent corruption of the type itself. Two stack a second, unrelated flavour of laziness on top: deferring delivery of the code across a network boundary, with its own syntax and its own failure modes. The big-O is identical everywhere. Almost nothing else is.

Lazy Loading in JavaScript: what you actually reach for

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.

JavaScript implementation

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 matching review note is to clear the slot in a .catch so the rejection is not cached for the process lifetime, because a retained rejected promise turns one flaky fetch into a permanent outage. Keep await import() inside a function body too: a top-level await makes the whole module async, and every module importing it now waits on work you meant to defer.
javascript
// 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 Free

The JavaScript-specific trap

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.

Performance in JavaScript, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Lazy Loading between languages.

Real-World Applications

Lazy Loading is used extensively in production software: web frameworks, content management systems, API gateways, and SPA architectures implement this pattern for handling HTTP requests and rendering. In JavaScript, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Lazy Loading helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Lazy Loading appears frequently in phone screens and early-round coding interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Lazy Loading over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Lazy Loading to build pattern recognition. In JavaScript, demonstrate proficiency with closures and async/await to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic JavaScript code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Before paying for Replit, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.