Saturday, September 14, 2013

How do you write a function that does not run until the rest of the js file has been parsed

How do you write a function that does not run until the rest of the js
file has been parsed

Let's say I have some function on top of a script that, when given a hash
mapping function name {string} to functions defined below it, so in code:
collect({"f1" : f1, "f2" : f2 })
The problem is if collect is at the top of the page, then f1, f2, .. will
point to undefined since those functions have, yet to be defined. The easy
solution is to put collect at the bottom of the page. But if I stubbornly
need it to sit at the top, how do I delay execution of collect until all
other functions are parsed?
Note, the rest of the functions are defined in form:
var name;
name = function(){ .. }
Bonus question:
If I can define collect such that instead of passing in a has mapping name
to function, I can just pass in a list of functions, or a list of strings,
and achieve the same effect, it would be even better. So in code,
something like
collect([f1,f2])
collect(["f1","f2"])
Update: I think I'm not being explicit about what I am asking. I am
looking specifically to delay the execution of a function until the rest
of the file is parsed. I am not looking to replicate this behavior via
some other hack that changes the semantics of what I am trying to do.

No comments:

Post a Comment