1

I'm trying to load a script so I can use scripts on the page that is spawned by the bookmarklet. (view src: XHR followed by beautify.js followed by prettify.js)

I know what I am basically supposed to do (like this) but what's happening is I can't find a good way to detect when the functions I need are actually loaded.

var doWhenLoaded = function (name) {
    if (typeof(eval(name)) === 'function') {
        eval(name+'()');
    } else {
        setTimeout( 
            function () {
                console.log("from timeout: "+new Date().getTime());
                doWhenLoaded(name,call); 
            } , 50 
        );
    }
}   

I tried that but eval(name+'()'); throws an error.

Community
  • 1
  • 1
Steven Lu
  • 41,389
  • 58
  • 210
  • 364

2 Answers2

0

I can't answer your question, but to test if a function is available use:

var doWhenLoaded = function (name) {   
    if (typeof window[name] == 'function') {
      window[name]();
    } else {
      // set the timeout. Should have a limit, else it wil go on forever.
    }
    ...
};

Edit

Updated to use window[name], but really should use a reference to the global object. But I guess it's ok to use window for a browser specific script.

The code above should not throw any errors. Since name is in the formal parameters, it's essentially a declared local variable. If name is undefined, then typeof name will return the string "undefined", which fails the test so name() is not evaluated.

RobG
  • 142,382
  • 31
  • 172
  • 209
  • Okay. I can't get this to work. Any time I call doWhenLoaded, if name is undefined I get an error! I also cannot get Chrome to give me a line number for the error. :( – Steven Lu Apr 02 '12 at 02:29
  • Is what I'm trying to do simply impossible? I'm loading scripts in the new window made by the bookmarklet. How to run my test-check function in that window's "context"? – Steven Lu Apr 02 '12 at 02:43
0

I think I can force the scripts to get loaded synchronously before I end up calling them by simply writing the document rather than setting them into the dom.

Steven Lu
  • 41,389
  • 58
  • 210
  • 364