Last active
December 18, 2015 15:58
-
-
Save frostney/5807994 to your computer and use it in GitHub Desktop.
Asynchronous module loader in about 50 lines of CoffeeScript. It's not a script loader though, all modules have to be in one file
This file contains hidden or 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
do (root = if exports? then exports else @) -> | |
defined = [] | |
modules = {} | |
evaluateModules = (ids, callback, after) -> | |
ids = [ids] if typeof deps is 'string' | |
depList = [] | |
depLength = ids.length | |
depIndex = 0 | |
for dep, num in ids | |
evaluateSingleModule dep, (depResult) -> | |
depList[num] = depResult | |
depIndex++ | |
if depIndex is depLength | |
if after | |
after modules[dep].cache = callback.apply @, depList | |
else | |
callback.apply @, depList if callback? | |
null | |
evaluateSingleModule = (id, callback) -> | |
return unless modules[id] | |
# If cache available, use the cache | |
return callback(modules[id].cache) if Object.hasOwnProperty modules[id], 'cache' | |
{factory} = modules[id] | |
unless modules[id].deps? | |
callback modules[id].cache = if typeof factory is 'function' then factory.apply @ else factory | |
else | |
evaluateModules modules[id].deps, factory, callback | |
root.define = (id, deps, factory) -> | |
return if defined.indexOf(id) > 0 | |
if Array.isArray deps | |
deps = null if deps.length is 0 | |
else | |
[deps, factory] = [null, deps] | |
defined.push id | |
modules[id] = {deps, factory} | |
root.define.amd = true | |
# Uncomment this for debug purposes | |
#root.modules = modules | |
root.require = evaluateModules |
This file contains hidden or 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
define 'a', -> 1 | |
define 'b', -> 2 | |
define 'c', ['a', 'b'], (a, b) -> a + b | |
define 'd', ['c', 'b', 'a'], (c, b, a) -> c * (b + a) | |
define 'e', ['d'], (d) -> d * 3 | |
require ['e'], (e) -> console.log e |
This file contains hidden or 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
amara = require './amara' | |
amara.define 'a', -> 1 | |
amara.define 'b', -> 2 | |
amara.define 'c', ['a', 'b'], (a, b) -> a + b | |
amara.define 'd', ['c', 'b', 'a'], (c, b, a) -> c * (b + a) | |
amara.define 'e', ['d'], (d) -> d * 3 | |
amara.require ['e'], (e) -> console.log e |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment