3 ms·
Too bad we can’t have php style autoloading in JS. Actually what I really want is to lazy-load modules on demand! So if something is concatenated into a giant
by EGreg 7y ago
Too bad we can’t have php style autoloading in JS.
Actually what I really want is to lazy-load modules on demand! So if something is concatenated into a giant file then I don’t need to load modules anymore.
Like maybe this:
function load(module) {
if (load.loaded[module]) return;
import(module)
.then(() => load.loaded[module] = true);
}
- Ndymium 7y agoYou could probably write such a thing using the dynamic `import()` that is quite supported: https://caniuse.com/#feat=es6-module-dynamic-import https://caniuse.com/#feat=es6-module-dynamic-import In fact it's most likely someone has already done that.
- 6510 7y agohttp://neanderthal.go-here.nl http://neanderthal.go-here.nl
- Can_Not 7y agoI actually don't see why someone couldn't write a PHP style autoloader for JS, there is already a lot of cool hacks around require. I think a simple autoloader would just do something like (almost pseudocode): find src/**/*.{js,ts} -exec cat {} | typescript >> build.js
- frozenlettuce 7y agoYou can create a function to dinamycally add script tags to load other pieces of code, but you would end up implementing a whole module system.
- EGreg 7y agoA long time ago we just implemented two methods: Q.exports(a, b, c) Q.require(src, callback) Following node but just async. It’s simple and it works. We were able to know the name of the latest loaded js file in exports() by a trick of throwing an exception and catching it to see what script was on the top of the stack. All browsers seem to support this. Since it worked back then, we didn’t need anything else. It is super simple to just keep using those things and replace the middleware underneath to whatever is the standard du jour. It's super short and simple, you can implement similar things in your projects: https://github.com/Qbix/Platform/blob/master/platform/plugins/Q/web/js/Q.js#L7842 https://github.com/Qbix/Platform/blob/master/platform/plugin... https://github.com/Qbix/Platform/blob/master/platform/plugins/Q/web/js/Q.js#L7826 https://github.com/Qbix/Platform/blob/master/platform/plugin...
- aliswe 7y agoIt qas a few montgs since I used it, bit it wprks basically exactly like you want, only ghat the "is loaded" check isn't needed, the module is global and may even be a singleton.