views:

40

answers:

1

How do i add my javascript file as an embeded resource to the page after the ajax javascript already on the page? NB want to do this part dynamically to have code wrapped up in usercontrol.

in aspx page: scriptmanager

Code: Assembly: WebResource("Functions.js", "text/javascript")

Code: onPreRender:

ScriptManager.RegisterClientScriptResource(Me.Page, Me.GetType().BaseType, "Functions.js")

This code successfully adds my javascript code to the page but not after the AJAX javascript and so not all of my functions work correctly.

Thanks, Dave

+1  A: 

You could use GetWebResourceUrl() to get the path string to your embeded script as it should be in the page (probably something like websresource.axd?XXXX). Then manually insert a script tag pointing to the path using RegisterStartupScript to force it to be added at the end of the page. Something like below...

path = ScriptManager.GetWebResourceUrl(this.GetType(), "Fucntion.js");
ScriptManger.RegisterStartupScript(this.GetType(), "MyScript", "<script type=\"text/javascript\" src=\"" + path + "\"/>");

From the server you could also try adding your script later in the load process for example in the prerender event. Or from the client side can wrap your script into a load so that it doesn't run the code until the last possible moment as below...

function RunOnLoad()
{

     button.onclick = function()
     {
       alert("Clicked!");
     }

}
window.onload = RunOnLoad;
Lee Hesselden
have tried the below, it manages to register the javascript file but appears in the webpage before the ajax javascripts and so the functionality does not work, is there a way to specify the order ie add it aftwards.ScriptManager.RegisterStartupScript(Me.Page, Me.GetType, pKey, strJava, False)
Dave
Do you have control over when the Ajax script is added as I believe it is simply down to the order added? You could also amend the script file you are including to prevent it from running immediately. For example attach to the onload in your script or do a settimeout?
Lee Hesselden
The ajax script is added by the ScriptManager automatically and so dont have control over when it is added. The javascript file only has functions that are called by user event i.e button click, but its code needs to reference an ajax object created by the ajax code and so there is a null refrernce error if js file is added before ojbect is created
Dave
Are you currently inserting the script during the server side page_load event? If so have your tried adding your script reference during a later event possible the prerender event? You could also wrap you script file into a load and attach your event functions there (see update).
Lee Hesselden
Solved the problem using... ScriptManager.RegisterStartupScript(Control, Me.GetType, pKey, strJava, False) instead of adding to page have added to a control which is rendered later in the page. thanks for your help
Dave