I have two coffeescript files, A and B, in the same folder. I want A to execute up to a point, then run B, then continue executing. In other words, I want this:
//in A
$("#content").html(@currentView.el)
require ['B']
//in B
if document.location.href.indexOf("showdiv") > 0
$("#content").trigger('click')
However, if I put everything into A, it works fine:
//in A
$("#content").html(@currentView.el)
if document.location.href.indexOf("showdiv") > 0
$("#content").trigger('click')
How can I get the first snippet to work? Is the require keyword making the compiled javascript load in parallel?
In the browser you control the load order by how you pull in your code in your html file. Here’s an example from one of my projects (in
index.html, just before the closingbodytag):The last one is the one that kicks things off, similar to the “main” function in C if that makes any sense to you. In it, there is this construct (compiled to js of course):
The initialization code will either include all the code in your original posting (minus the require calls which do not exist in the browser), or call a function containing it. The reason you need to delay your script execution in the manner shown above is to delay execution until all the code has loaded properly.
There are other ways to do it, and one you may be confusing with is the concept of Javascript AMD (Asynchronous Module Definition) and you can read more about it on one of the libraries for it (RequireJS – http://requirejs.org). But my advice would be to master the basics as I’ve described above before trying to get AMD (with tools) going.