How does lazy loading work?

Srecko Kostic
2 min readApr 30, 2022

Lazy loading works by adding the script tag to the DOM. The script tag has an src attribute that points to the JavaScript chunk.

closure with code that adds click event that appends script pointing to the chunk to the dom
closure with code that adds click event that appends script pointing to the chunk to the dom

Note: The example is simple for ease of understanding.

  1. The JavaScript chunk with code exists alongside other code.
  2. The main bundle adds the script tag with src pointing to the JavaScript chunk in the DOM.
  3. The code from the JavaScript chunk is available.

Code in the JavaScript files has global scope, and other files can use it. After the script becomes available in the DOM, it loads the chunk content, and the main bundle can use it.

Repository with the complete source code

Here is the complete source code, comments, and readme file with instructions https://github.com/srele96/how-does-lazy-loading-work.

Steps to recreate the example

  1. Create index HTML file.
  2. Add the button with an id in the index HTML file.
  3. Add the script tag that points to the main JavaScript bundle.
  4. The button from the main JavaScript bundle should call a function to load the chunk.
  5. The function should create the script with src pointing to the JavaScript chunk and append it to the DOM.
  6. After clicking the button, the code from the JavaScript chunk is available.

Note: The browser needs to download the chunk like any other file. That means the code won’t be available immediately.

If you want to verify that the browser downloads the chunk, go to the Network tab in the browser. Then click the button to load the JavaScript chunk. There should be a request with a chunk name.

--

--

Srecko Kostic

I create content from my perspective on topics I learn. Some information may be incorrect, but I hope some find my content useful.