Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does coffeescript have an onLoad like event for the browser

Tags:

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 "I've finished loading all the coffee files"

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

like image 246
Steven Noble Avatar asked Jan 19 '23 06:01

Steven Noble


1 Answers

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>

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

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>

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()

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

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.)

like image 178
Trevor Burnham Avatar answered Jan 21 '23 19:01

Trevor Burnham