How can I lazily-load ES6 modules? By lazy, I mean I don't want to actually load modules that aren't needed. For example, here's something I can do with RequireJS:
function someEventHandler() {
var SomeModule = require('some-module'),
module = new SomeModule();
// ...
}
Something along the same lines doesn't appear to be possible using ES6 imports:
// Doesn't appear to be valid...
function someEventHandler() {
import SomeModule from 'some-module';
var module = new SomeModule();
// ...
}
Are there any viable techniques to only pull in dependencies when needed, using ES6 modules? Or is the only path to trace the full dependency graph and fetch everything up-front?
Lazy loading is a technique for waiting to load certain parts of a webpage — especially images — until they are needed. Instead of loading everything all at once, known as "eager" loading, the browser does not request certain resources until the user interacts in such a way that the resources are needed.
Native lazy loading API Lazy loading is built on top of the Intersection Observer API, which is a browser API that provides a way of detecting or knowing when an element called a target, a parent element, or becomes available or visible inside the browsers viewport, as the case may be.
Lazy loading is an approach to limit the modules that are loaded to the ones that the user currently needs. This can improve your application's performance and reduce the initial bundle size. By default, Angular uses eager loading to load modules.
Lazy loading modules helps us decrease the startup time. With lazy loading our application does not need to load everything at once, it only needs to load what the user expects to see when the app first loads. Modules that are lazily loaded will only be loaded when the user navigates to their routes.
The import
statement will only work in the very top of files, and it will load all of them. This is mainly to avoid potential issues with circular dependencies.
There will also be a way to do asynchronous loading; however the specification doesn't seem to be finalized yet. The ES6 module loader polyfill package uses a method called System.import(moduleName)
that returns a promise and the final specification is likely to look similar:
function someEventHandler() {
System.import('some-module').then((SomeModule) => {
var module = new SomeModule();
// ...
})
}
Example for lazyloading jQuery in ES6 :
import('jquery').then((jquery) => {
// Because jquery is the module, here is the new syntax for using this
window.$ = jquery.default;
window.$('#id');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With