views:

228

answers:

2

I have a composite control on an ASPX page. There is Javascript on the ASPX page that gets loaded before the control. Now, since the script refers to the control element which does not exist when the script is loaded, this is throwing a Javascript error of "Obect not defined". Attaching the script to the onload event of the control gives "Sys not defined".

Any Idea?

The script is in an external file.

+3  A: 

You need to either move the Javascript function below the control creation, or add it inside a window.load event handler (jQuery and Prototype can help you for that), so you guarantee that the Javascript is called when the page has loaded and not before.

pgb
+2  A: 

You can keep the script in the load method of your control, although really it should be placed in the PreRender because then you can include it or not include it based on the state of the control. This would save you from javascript errors in the future where it says "Object cannot be found" because you have made the control invisible.

The reason you're getting "Sys is not defined" is because your script is being placed before the MicrosoftAjax.js file has loaded. Try something like this:

Dim yourScript as String = "Sys.Application.add_load(function() { /*code here*/ } )"
ScriptManager.RegisterStartupScript(Page, Me.GetType(), "ScriptKey", yourScript, true)

Otherwise you could use Page.ClientScript to hook into the document ready event if using the Sys namespace is not a requirement, but it sounds like from your question it is.

Edit:

Instead of RegisterStartupScript you're probably looking for RegisterClientScriptBlock, sorry, the two have different functionality.

Dave L