Tags
text/coffeescript
have a key difference from text/javascript
tags. They do not start until the document is loaded. This is because the coffee script library must find all the coffee script tags and compile them, and it must wait until the DOM is ready so that it can find all of them.
Another problem is that jQuery immediately starts the DOM callback if this event has already occurred. And in this case he has.
So, when this compiled in JS, you will get the following:
var sayHi; $(function() { return sayHi(); }); sayHi = function() { return alert('Hi there!'); };
So what happens:
- declare a
sayHi
variable without a value, making it undefined
. - Create a DOM callback for jQuery that uses this variable.
- jQuery starts the callback function right away, since the DOM is ready already.
- The callback function executes and tries to run
sayHi()
, which is still undefined. - After the callback is completed,
sayHi
installed on the function you want to run.
Now, if it was a regular JS tag, it could be launched before the document was loaded, and then it would work fine, because after a while the callback was actually sayHi
, then sayHi
would be assigned properly.
To fix this, you must assign a function BEFORE you start the pass in the callback. Or you can skip executing $(->)
completely since you already know that the DOM is ready. But actually, this is one of the main reasons you really shouldn't use coffeescript tags. This is really not the same as using the JS tag. And one of the many reasons for this is not the recommended approach to using CoffeeScript on a real site.
Compile your coffee script before your browser sees it as a responsible developer :)
Alex wayne
source share