Coffeescript 是否有类似 onLoad 的浏览器事件 [英] Does coffeescript have an onLoad like event for the browser

查看:20
本文介绍了Coffeescript 是否有类似 onLoad 的浏览器事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

coffeescript 编译并运行标头中的所有脚本文件后,有没有办法在浏览器中运行一些代码?比如:

Is there a way to have some code run in the browser after coffeescript has compiled and run all the script files in the header? Something like:

coffee.onCompiled() -> console.log "我已经加载完所有咖啡文件"

coffee.onCompiled () -> console.log "I've finished loading all the coffee files"

我还能如何获得这种行为?(请不要建议setTimeout)

How else can I get this behaviour? (please don't suggest setTimeout)

推荐答案

起初我以为你问的是如何从 CoffeeScript 将回调附加到 window.onload(当然,非常简单,因为它只是 JavaScript"),但现在我意识到你在问如何确保代码运行

At first I thought you were asking about how to attach a callback to window.onload from CoffeeScript (which is, of course, very straightforward, since "It's just JavaScript"), but now I realize that you're asking how you ensure that code runs after all

<script type="text/coffeescript" src="..."></script>

使用 coffee-script.js 时已执行标记.

tags have been executed when using coffee-script.js.

一种解决方案是在您加载的最后一个 CoffeeScript 中放置一个回调.从 1.1.0 开始,coffee-script.js 已确保所有 CoffeeScript script 标签按顺序运行(但请注意,它们只会在所有 JavaScript 之后运行script 标签已运行).所以,例如,如果你把

One solution is to put a callback in the last CoffeeScript you load. Since 1.1.0, coffee-script.js has ensured that all CoffeeScript script tags are run in order (though note that they'll only run after all JavaScript script tags have run). So, for instance, if you put

<script type="text/coffeescript">
  onReady()
</script>

在所有其他 script 标记之后,并在其他地方定义 window.onReady,然后在所有脚本加载后调用该函数.如果你成功了

after all your other script tags, and define window.onReady somewhere else, then that function will be called after all scripts have loaded. If you made it

 $ -> onReady()

(使用 jQuery),那么您将确保 DOM 以及所有脚本都已准备好.

(with jQuery), then you'd ensure that the DOM is ready as well as all scripts.

更新:我发布说这是一种解决方案",因为我不能 100% 确定 coffee-script.js 在所有脚本之后是否调用回调已运行.但是在查看来源之后,我可以自信地说它没有,所以 only 解决方案是将代码放在最后一个 <script type="text/coffeescript"> 标记中.(不管是内联的还是 .coffee 文件中的.)

Update: I posted that this is "one solution" because I wasn't 100% sure whether there's a callback that coffee-script.js invokes after all scripts have been run. But after checking the source, I can confidently say that it doesn't, so the only solution is to put code in the last <script type="text/coffeescript"> tag. (Whether it's inline or in a .coffee file doesn't matter.)

这篇关于Coffeescript 是否有类似 onLoad 的浏览器事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆