UNPKG

1.65 kBtext/coffeescriptView Raw
1window.CoffeeScript = require './module'
2
3# Use standard JavaScript `eval` to eval code.
4CoffeeScript.eval = (code, options = {}) ->
5 options.bare ?= on
6 options.optimise ?= on
7 eval CoffeeScript.cs2js code, options
8
9# Running code does not provide access to this scope.
10CoffeeScript.run = (code, options = {}) ->
11 options.bare = on
12 options.optimise ?= on
13 do Function CoffeeScript.cs2js code, options
14
15# Load a remote script from the current domain via XHR.
16CoffeeScript.load = (url, callback) ->
17 xhr = if window.ActiveXObject
18 new window.ActiveXObject 'Microsoft.XMLHTTP'
19 else
20 new XMLHttpRequest
21 xhr.open 'GET', url, true
22 xhr.overrideMimeType 'text/plain' if 'overrideMimeType' of xhr
23 xhr.onreadystatechange = ->
24 return unless xhr.readyState is xhr.DONE
25 if xhr.status in [0, 200]
26 CoffeeScript.run xhr.responseText
27 else
28 throw new Error "Could not load #{url}"
29 do callback if callback
30 xhr.send null
31
32# Activate CoffeeScript in the browser by having it compile and evaluate
33# all script tags with a content-type of `text/coffeescript`.
34# This happens on page load.
35runScripts = ->
36 scripts = document.getElementsByTagName 'script'
37 coffees = (s for s in scripts when s.type is 'text/coffeescript')
38 index = 0
39 do execute = ->
40 return unless script = coffees[index++]
41 if script.src
42 CoffeeScript.load script.src, execute
43 else
44 CoffeeScript.run script.innerHTML
45 do execute
46 null
47
48# Listen for window load, both in browsers and in IE.
49if addEventListener?
50 addEventListener 'DOMContentLoaded', runScripts, no
51else if attachEvent?
52 attachEvent 'onload', runScripts