Last active
November 22, 2020 15:37
-
-
Save felixmosh/088657e92390d7450c94216f62ddc738 to your computer and use it in GitHub Desktop.
AngularJS (>=1.6.7) lazy load modules without ocLazyLoad
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
} | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export angular.module('lazyLoadedModule', []) | |
.component('someComponent', ...) | |
.name; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]); | |
}); | |
}); | |
} | |
} |
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
Just wanted to say, thanks again! I reference your gist in my post: https://www.bennadel.com/blog/3929-proof-of-concept-injecting-features-into-an-invision-share-link-experience-using-angularjs-1-6-7.htm