Skip to content

Instantly share code, notes, and snippets.

@felixmosh
Last active November 22, 2020 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felixmosh/088657e92390d7450c94216f62ddc738 to your computer and use it in GitHub Desktop.
Save felixmosh/088657e92390d7450c94216f62ddc738 to your computer and use it in GitHub Desktop.
AngularJS (>=1.6.7) lazy load modules without ocLazyLoad
import { LazyLoader } from './LazyLoader';
import uiRouter from '@uirouter/angularjs';
angular.module('myApp', [uiRouter])
.service('lazyLoader', LazyLoader)
.config(($stateProvider) => {
$stateProvider
.state('some-state', {
url: '/some-state',
lazyLoad: ($transition$) => {
return $transition$
.injector()
.get('lazyLoader').loadModules('../path-to/lazyLoadedModule.js');
}
});
});
export angular.module('lazyLoadedModule', [])
.component('someComponent', ...)
.name;
export class LazyLoader {
constructor($injector, $rootScope) {
this.$injector = $injector;
this.$rootScope = $rootScope;
}
async loadModules(bundleUrl) {
const moduleName = await import(bundleUrl);
const alreadyLoadedModules = Object.keys($injector.modules);
$injector.loadNewModules([moduleName]);
const newModules = Object.keys($injector.modules)
.filter(moduleName => alreadyLoadedModules.indexOf(moduleName) === -1);
// Notify of component loaded similar to ocLazyLoad.componentLoaded (https://oclazyload.readme.io/docs/oclazyloadprovider)
newModules.forEach((moduleName) => {
// This is a private usage, it may break in the future.
$injector.modules[moduleName]['_invokeQueue'].forEach(([_, type, [typeName]]) => {
$rootScope.$broadcast('componentLoaded', [moduleName, type, typeName]);
});
});
}
}
@felixmosh
Copy link
Author

felixmosh commented Feb 17, 2019

This example requires angularJS 1.6.7 and above, it uses the new $injector.loadNewModule api.

I've added a small example of how to mimic ocLazyLoad events of the new loaded module.
⚠️ Pay attention, it uses internal api _invokeQueue, and it may break in the future. (tested with latest angularJs version [1.7.7] and it works).

@bennadel
Copy link

Oh awesome! I've been on AngularJS 1.2.22 for so long, I had no idea that there was any movement on lazy-loading in later version. This is exciting (for those of us who can't migrate to Angular 11 anytime soon).

@bennadel
Copy link

@felixmosh
Copy link
Author

I'm happy that you found it useful for you :]

Thanx for the credit.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment