CoffeeScript = require './coffee-script'
CoffeeScript.require = require
compile = CoffeeScript.compile
这个 **浏览器** 兼容性层扩展了核心 CoffeeScript 函数,以便在浏览器中直接编译代码时能顺利运行。我们添加了对通过 **XHR** 加载远程 Coffee 脚本的支持,以及 text/coffeescript
脚本标签、通过 data-URL 的源映射等等。
CoffeeScript = require './coffee-script'
CoffeeScript.require = require
compile = CoffeeScript.compile
使用标准 JavaScript eval
来评估代码。
CoffeeScript.eval = (code, options = {}) ->
options.bare ?= on
eval compile code, options
运行代码无法访问此范围。
CoffeeScript.run = (code, options = {}) ->
options.bare = on
options.shiftLine = on
Function(compile code, options)()
如果我们不在浏览器环境中,我们就完成了公共 API 的工作。
return unless window?
尽可能包含源映射。如果我们有 base64 编码器、JSON 序列化器和用于转义 Unicode 字符的工具,我们就可以开始了。从 https://mdn.org.cn/en-US/docs/DOM/window.btoa 移植而来
if btoa? and JSON?
compile = (code, options = {}) ->
options.inlineMap = true
CoffeeScript.compile code, options
通过 XHR 从当前域加载远程脚本。
CoffeeScript.load = (url, callback, options = {}, hold = false) ->
options.sourceFiles = [url]
xhr = if window.ActiveXObject
new window.ActiveXObject('Microsoft.XMLHTTP')
else
new window.XMLHttpRequest()
xhr.open 'GET', url, true
xhr.overrideMimeType 'text/plain' if 'overrideMimeType' of xhr
xhr.onreadystatechange = ->
if xhr.readyState is 4
if xhr.status in [0, 200]
param = [xhr.responseText, options]
CoffeeScript.run param... unless hold
else
throw new Error "Could not load #{url}"
callback param if callback
xhr.send null
通过让 CoffeeScript 编译并评估所有内容类型为 text/coffeescript
的脚本标签,在浏览器中激活 CoffeeScript。这在页面加载时发生。
runScripts = ->
scripts = window.document.getElementsByTagName 'script'
coffeetypes = ['text/coffeescript', 'text/literate-coffeescript']
coffees = (s for s in scripts when s.type in coffeetypes)
index = 0
execute = ->
param = coffees[index]
if param instanceof Array
CoffeeScript.run param...
index++
execute()
for script, i in coffees
do (script, i) ->
options = literate: script.type is coffeetypes[1]
source = script.src or script.getAttribute('data-src')
if source
CoffeeScript.load source,
(param) ->
coffees[i] = param
execute()
options
true
else
options.sourceFiles = ['embedded']
coffees[i] = [script.innerHTML, options]
execute()
监听窗口加载,在正常的浏览器和 IE 中都监听。
if window.addEventListener
window.addEventListener 'DOMContentLoaded', runScripts, no
else
window.attachEvent 'onload', runScripts