I will start with a simple question How long will you wait for a website to load?
As per google recommendation, a website page should load within 2 seconds,
“Two seconds is the threshold for ecommerce website acceptability. At Google, we aim for under a half-second.”
but still, you may have encountered many websites that take a long time for initial loading which results in a terrible user experience.
Usually, when we build web apps which is of the medium or large scale we usually end up using many JavaScript libraries, CSS framework, images, etc. which ultimately results in a bigger bundle size.
But we can configure our app to split that bigger bundle into smaller chunks and load them when they are required. This strategy called Lazy loading
Lazy loading
As the name suggests, in this strategy you will not load resources (JS, CSS, Images) until it is required. For example, let see a small demo
I the above GIF I am trying to show a calendar on a webpage that is initially hidden and will be shown when the user clicks on the "Show calendar" link
If you have noticed that there are additional JS files requested when I clicked on the "Show calendar" link. Those JS files are related to the calendar but we requested them only when we actually need them.
This makes our initial page load faster by not shipping unused code to the browser as you can see below images the percentage of unused code in both the cases
Without lazy loading
With lazy loading
This also helps in reducing bandwidth usage as we only need to load a few resources rather than all regardless of their usage
Eager loading
In Eager loading approach is we try to load or initialize all the resources available as soon as our web pages loaded. Quite opposite of Lazy loading. Eager loading also involves pre-loading of related resources.
It looks bad approach initially but this is very useful for below use cases
- Small applications where you can load all the resources without much waiting time
- Few API calls to put to reduce stress on server
- Background downloading of related objects
Lazy loading with Webpack
If you are using Webpack as your bundler then you can use import(...)
syntax to lazy load resources. With Magic comments, how our chuck should be loaded
'lazy' (default): Generates a lazy-loadable chunk for each imported module.
function component() {
const element = document.createElement('div');
const _ = await import(/* webpackMode: "lazy" */ 'lodash');
const button = document.createElement('button');
const br = document.createElement('br');
button.innerHTML = 'Click me and look at the console!';
element.innerHTML = _.join(['Hello', 'webpack'], ' ');
element.appendChild(br);
element.appendChild(button);
return element;
}
document.body.appendChild(component());
Dynamic import i.e. import()
statement also works with Parcel
Top comments (0)