Skip to content

Instantly share code, notes, and snippets.

@felixmosh
Last active November 22, 2020 15:37
Show Gist options
  • 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]);
});
});
}
}
@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