How does lazy loading work?
Lazy loading works by adding the script tag to the DOM. The script tag has an src attribute that points to the JavaScript chunk.
Note: The example is simple for ease of understanding.
- The JavaScript chunk with code exists alongside other code.
- The main bundle adds the script tag with src pointing to the JavaScript chunk in the DOM.
- 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
- Create index HTML file.
- Add the button with an id in the index HTML file.
- Add the script tag that points to the main JavaScript bundle.
- The button from the main JavaScript bundle should call a function to load the chunk.
- The function should create the script with src pointing to the JavaScript chunk and append it to the DOM.
- 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.