views:

167

answers:

3

How can I in jQuery test when a javascript function is fully loaded? I would like to use a gif, which displays loading, while the javascript function loads, and hide it when the function is fully loaded?

+2  A: 

Just call yourself after defining the function. The statements after the function definition will only be executed after the preceding source text is read (and thus executed).

David Schmitt
that's not what was asked, you are assuming he is not dynamically loading a script via $.getScript
Chad Grant
+3  A: 
$(function(){
    $("#loadingGIF").show();
    WaitForFunction();
});

function WaitForFunction()
{
    if (!$.isFunction(FUNCTION_TO_WAIT_ON_HERE)) {
       setTimeout( WaitForFunction, 100);
       return;
    }
    Function_Loaded();
}

function Function_Loaded(){
      $("#loadingGIF").hide();
}
Chad Grant
Wouldn't a loop be better than recursion here? Granted, it shouldn't take too terribly long to download the script, but if there is a network error the stack'll overflow and performance will decrease or the browser will crash.
jimktrains
There is no recursion in the code I posted.
Chad Grant
A: 

I'm not sure what you mean by loading but the following should apply anyway:

  1. When you start loading the JavaScript code, display the GIF
  2. In the code you load, add a statement to hide the GIF at the end

This should solve your problem in a "simple" way without having to use timers, etc.

Aaron Digulla