Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until function is loaded

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?

like image 248
Dofs Avatar asked Apr 27 '09 11:04

Dofs


People also ask

How do you execute a function when a page is fully loaded?

Method 1: Using onload method: The body of a webpage contains the actual content that is to be displayed. The onload event occurs whenever the element has finished loading. This can be used with the body element to execute a script after the webpage has completely loaded.

How do you wait for an async function to finish?

async and await Inside an async function, you can use the await keyword before a call to a function that returns a promise. This makes the code wait at that point until the promise is settled, at which point the fulfilled value of the promise is treated as a return value, or the rejected value is thrown.


3 Answers

$(function(){
    $("#loadingGIF").show();
    WaitForFunction();
});

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

function Function_Loaded(){
      $("#loadingGIF").hide();
}
like image 186
Chad Grant Avatar answered Oct 12 '22 06:10

Chad Grant


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).

like image 26
David Schmitt Avatar answered Oct 12 '22 06:10

David Schmitt


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.

like image 31
Aaron Digulla Avatar answered Oct 12 '22 06:10

Aaron Digulla