Skip to content

Instantly share code, notes, and snippets.

@frostney
Last active December 18, 2015 15:58
Show Gist options
  • Save frostney/5807994 to your computer and use it in GitHub Desktop.
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
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
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
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