laconicdev
laconicdev

Reputation: 6440

javascript function called is undefined while parts of the page are loading

I have an aspx page that includes a javascript file in the head tag. This page has a user control placed on it. The user control has a link with an inline javascript function that references an object that is defined in the javascript file loaded on aspx page. The application consists of a master page and a number of other aspx pages. The page in question (with the javascript file) loads before any other page, and the link with the javascript file is rendered. However, if I click on the link, I get an error, saying "Microsoft JScript runtime error: 'Foo' is undefined". Where foo is an object defined in the javascript file. However, if I wait until all the parts of the page are loaded, the link works fine. What is happening here? How can I prevent this error from happening?

Thanks.

Upvotes: 0

Views: 818

Answers (1)

Roatin Marth
Roatin Marth

Reputation: 24105

if I wait until all the parts of the page are loaded, the link works fine

That says to me the browser hasn't finished retrieving and executing the js file by the time you have clicked the link with the inline function.

One potential solution is to wait until the page has loaded to attach your click handler:

window.onload = function() {
  var link = document.getElementById('myLink');
  link.onclick = function() {
    // on click logic
  }
}

This is just an example. This would be placed along inside your js file so as to load all dependencies at once.

It's a little hard to be more specific as you've generalized quite a bit in your question.

Upvotes: 1

Related Questions