{
  "id": "lazy-loading",
  "title": "Lazy Loading",
  "lang": "en",
  "source_lang": "en",
  "summary": "Lazy loading defers loading resources or data until they are needed, reducing initial work while potentially increasing first-access latency and implementation complexity.",
  "category": "computer-science",
  "subcategory": "software",
  "type": "concept",
  "aliases": [
    "On-demand loading",
    "Deferred loading"
  ],
  "generated_at": "2026-11-06",
  "model": "pro/gpt-6.1-sol",
  "url": "https://aiwiki.page/en/lazy-loading/",
  "translations": {
    "zh-Hans": {
      "url": "https://aiwiki.page/zh/lazy-loading/",
      "json": "https://aiwiki.page/zh/lazy-loading.json"
    }
  },
  "sections": [
    {
      "heading": "",
      "text": "Lazy loading is a software engineering technique that postpones loading a resource, retrieving data, or constructing an object until it is needed or likely to be needed soon. Instead of preparing every possible dependency in advance, a system initially provides only what is necessary for its current operation. The technique is used in web pages, application modules, databases, and memory management. Its main purpose is to reduce unnecessary work and improve startup or initial-response performance, although it can introduce delays and failures at the point of first use."
    },
    {
      "heading": "Principle and terminology",
      "text": "Lazy loading changes when work occurs, rather than necessarily changing what the work does. A resource that would otherwise be loaded during startup is represented by a reference, placeholder, loader function, or other lightweight substitute. A later event triggers the actual operation.\n\nIts opposite is eager loading, which loads resources before a particular access requires them. Neither approach is universally preferable: eager loading favors immediate availability, while lazy loading avoids spending resources on things that may never be used.\n\nSeveral related concepts are distinct:\n\n- Lazy initialization postpones creating or initializing an object. Lazy loading often includes lazy initialization, but may instead retrieve an already existing object from storage.\n- Lazy evaluation postpones evaluating an expression until its value is required. It concerns a programming language’s evaluation behavior, whereas lazy loading usually concerns resource availability.\n- Caching retains data or results for reuse. A lazily loaded resource may be cached afterward, but deferring a load and retaining its result are separate decisions.\n- Prefetching retrieves resources before explicit demand, based on an expectation that they will be needed. A system may combine lazy loading with prefetching to avoid both unnecessary startup work and excessive first-use delay.\n- Asynchronous programming allows an operation to complete without requiring the initiating execution flow to wait synchronously. A lazy load may be synchronous or asynchronous; an asynchronous operation need not be lazy.\n\nIn practical interfaces, “needed” is often defined approximately. An image may start loading shortly before it enters the visible area, rather than after it becomes visible."
    },
    {
      "heading": "How lazy loading works",
      "text": "A typical lazy-loading mechanism has four elements:\n\n- A deferred resource: an image, module, database relationship, file, or other item not yet loaded.\n- A trigger: an explicit request, property access, navigation event, visibility threshold, or memory access.\n- A loader: the operation that retrieves, decodes, imports, or constructs the resource.\n- State management: information recording whether the resource is unloaded, loading, available, or unavailable because of an error.\n\nFor an asynchronous resource, a useful model is a finite-state machine with transitions such as:\n\nunloaded → loading → loaded\n                   ↘ failed\n\nAn implementation may permit a failed load to be retried or a loaded resource to be invalidated. It may also retain the in-progress operation so that several callers share one request rather than starting duplicate loads.\n\nA placeholder can hide the fact that a resource is not yet available. For example, an object representing a database record may expose a property whose first access retrieves related records. Such transparency simplifies some calling code, but it can also conceal expensive operations behind apparently ordinary accesses."
    },
    {
      "heading": "Web content and applications",
      "text": "Images and embedded documents\n\nOn the World Wide Web, lazy loading commonly defers images and embedded documents that are outside the initial visible area. A web browser can then allocate network and processing capacity to resources needed for the first screen.\n\nHTML provides a loading attribute for images and inline frames. For example:\n\n<img\n  src=\"gallery-photo.jpg\"\n  loading=\"lazy\"\n  width=\"1200\"\n  height=\"800\"\n  alt=\"A coastal landscape\">\n\nHere, loading=\"lazy\" asks the browser to defer loading according to its own heuristics. It does not prescribe an exact distance from the visible area at which loading must begin. The declared dimensions allow the browser to reserve space before the image is available, reducing layout movement.\n\nScripts can implement more specialized behavior, such as fetching content when a placeholder approaches the visible region. However, excessive dependence on scripts can complicate accessibility, indexing, and operation when scripts fail or are disabled.\n\nImages needed immediately—especially a prominent image in the first screen—can appear later if unnecessarily deferred. Consequently, reducing initial downloads does not automatically improve perceived performance.\n\nApplication code\n\nWeb applications can delay downloading and evaluating code for features that are not initially used. Code splitting divides an application into separately loadable pieces, while lazy loading determines when those pieces are requested.\n\nIn JavaScript, a dynamic import can trigger such loading:\n\nasync function openEditor() {\n  const { createEditor } = await import(\"./editor.js\");\n  return createEditor();\n}\n\nWhether this produces a separate downloadable file depends on the application’s build and deployment system. The import mechanism also performs module loading and evaluation, rather than merely transferring bytes.\n\nTypical boundaries include routes, administration screens, editors, and infrequently used dialogs. Deferring these components can reduce startup work, but their first use may require a network round trip, parsing, evaluation, and initialization.\n\nLazy loading is not inherently tied to a user gesture. A system may initially defer a module and then prefetch it during an idle period or when navigation appears likely."
    },
    {
      "heading": "Databases and object relationships",
      "text": "In a database application, lazy loading often retrieves related data only when that relationship is accessed. An object-relational mapping system might initially load a customer record but defer its orders until the application requests them.\n\nThis can avoid transferring large related datasets that are never inspected. It can also produce the N+1 query problem:\n\n- One query retrieves \\(N\\) parent records.\n- Accessing a relationship on each parent causes another query.\n- The application performs \\(N+1\\) queries instead of a small number of combined or batched queries.\n\nThe performance penalty may be dominated by repeated database round trips rather than the number of returned rows. Eager fetching, batch loading, or explicitly shaped queries can reduce this cost, although fetching multiple collections together may instead produce large intermediate results.\n\nDeferred retrieval also affects correctness and resource lifetime. A later access may occur after the database session has closed, or outside the transaction that loaded the parent object. Depending on transaction isolation and application design, the retrieved related data may reflect a different database state.\n\nLazy database access can therefore make behavior less obvious: formatting a response, serializing an object, or displaying a property may unexpectedly execute SQL queries. Some systems consequently require explicit loading or prohibit implicit access in certain contexts."
    },
    {
      "heading": "Operating systems and storage",
      "text": "Operating systems use closely related demand-driven techniques. With demand paging, a process can have a valid virtual memory mapping without every associated page already being resident in physical memory. Accessing a nonresident page can trigger a page fault, after which the operating system supplies the page and resumes execution if the access is valid.\n\nThis illustrates the same broad principle as lazy loading, although demand paging is the more precise term in operating-system descriptions. It operates at the level of memory pages rather than application objects or web resources.\n\nMemory-mapped files and executable images can benefit from demand-driven access because unused portions need not all be brought into memory immediately. Actual behavior also depends on caching, read-ahead, and the storage system. A memory access that appears simple at the application level can therefore incur substantial input/output latency."
    },
    {
      "heading": "Performance trade-offs",
      "text": "The benefit of lazy loading depends on the probability that a resource will be used, its loading cost, and the overhead of deferral.\n\nIn a simplified model, let \\(c_i\\) be the cost of loading resource \\(i\\), \\(p_i\\) the probability that it is used during a session, and \\(H\\) the total overhead introduced by lazy-loading machinery. If every required resource is loaded once, with otherwise unchanged loading costs, expected work is approximately:\n\n\\[W_{\\text{lazy}} = H + \\sum_i p_i c_i\\]\n\nLoading every resource eagerly costs approximately:\n\n\\[W_{\\text{eager}} = \\sum_i c_i\\]\n\nThis model describes avoided work, not user-visible latency. It excludes effects such as batching, parallel requests, changing cache behavior, and contention. If nearly every resource is eventually used, lazy loading may save little overall work while adding scheduling and coordination costs.\n\nImportant trade-offs include:\n\n- Initial latency versus first-use latency: startup can improve while later interactions become slower.\n- Memory savings versus retention: deferral reduces memory use only while resources remain unloaded; it does not automatically unload them afterward.\n- Request reduction versus fragmentation: avoiding unused downloads can save bandwidth, but many small requests can introduce overhead and dependency chains.\n- Average performance versus predictability: inexpensive typical sessions may coexist with slow first accesses or occasional bursts of loading.\n\nEvaluation therefore distinguishes cold and warm operation, initial rendering, first interaction with deferred features, total transferred data, request counts, and memory consumption."
    },
    {
      "heading": "Reliability, concurrency, and security",
      "text": "Lazy loading moves some failures from startup to runtime. A missing file, unavailable service, permission error, or incompatible module may remain undetected until a particular feature is used. Interfaces may need explicit loading, error, retry, and fallback states.\n\nIn concurrent computing, several callers can attempt to load the same resource simultaneously. Implementations must define whether duplicate loads are acceptable or whether synchronization is required. Poorly coordinated initialization can cause a race condition, expose partially initialized state, or create a deadlock when loaders depend on one another.\n\nInvalidation introduces another difficulty: an older request may finish after a newer request and overwrite more recent state. Cancellation, version checks, and ownership rules can address such cases, depending on the environment.\n\nLazy loading does not provide access control. A resource is not protected merely because the initial interface does not download or display it. Authorization must still be enforced when the resource is requested. Deferred loading can also change when requests reveal user activity, making request timing relevant to privacy-sensitive applications."
    }
  ],
  "links": [
    "software-engineering",
    "asynchronous-programming",
    "finite-state-machine",
    "world-wide-web",
    "web-browser",
    "html",
    "web-accessibility",
    "javascript",
    "database",
    "object-relational-mapping",
    "database-transaction",
    "sql",
    "operating-system",
    "paging",
    "virtual-memory",
    "concurrent-computing",
    "synchronization-computing",
    "race-condition",
    "deadlock",
    "access-control"
  ],
  "sources": [],
  "license": "https://creativecommons.org/licenses/by/4.0/"
}