Thomas
Thomas

Reputation: 34188

How can I check a JavaScript function is loaded or exists in page before calling it?

Can anyone can give me a JavaScript code snippet by which I can detect if a JavaScript function is loaded in my aspx web page or exists before calling it?

Thanks

Upvotes: 6

Views: 7789

Answers (3)

Ivo Wetzel
Ivo Wetzel

Reputation: 46745

What do you mean by loaded?

In general you should use something like the onload event to make sure all your scripts have been loaded before you call them. In case you just want to whether a function has been declared or not you can use the typeof operator:

// Check the type of "myRandomFunction"
// Note: typeof is the only way you can use undeclared variables without raising an exception
if (typeof myRandomFunction === 'function') {
    myRandomFunction()
}

Upvotes: 1

batwad
batwad

Reputation: 3665

You could explicitly check that it's a function before calling it.

if (typeof(functionName) == "function")
    functionName();

Upvotes: 1

alex
alex

Reputation: 490233

This will check if your function is defined.

if (typeof functionName === 'function') {
  alert('loaded');
}

See it.

Upvotes: 13

Related Questions