First thing I would do is compare the output of the cgi to the html embedded within the cgi, make sure its not getting mangled.
Second, you might want to make sure the JavaScript doesn’t start until the body is loaded by either
2. Wrapping the main part of the script within a function call that is called after the body ( or target object ) loads.