How to ensure js is included in ascx file?

So the problem is this:

I have my own user control. which has some javascript file in the script tag included like this

<script type="text/javascript" src="../somefile.js" ></script> 

or javascript code directly on the ascx page. everything works if I put this control somewhere in aspx markup. but if I add this control to the page dynamically to some UpdatePanel place holder during postback (this is logical, I can’t change it), the control renders itself, and then I get a js error message that says that the functions which are placed in somefile.js are not defined / equal to zero. Why is this happening? In any case, you need to enable js, including in this case.

sorry that it is not specific enough, but the amount of code is huge, and I could not provide a simplified example with the same error.

The script is included, but somehow the functions are not defined. I am new to js, ​​so it is possible that only the script is included but not executed, so the functions are not declared ???

Interestingly, if on any page my user control is declared in aspx. Adding a few more instances dynamically does not cause problems.

+7
source share
3 answers

In the load event of your control, do something like this:

 if (!Page.ClientScript.IsClientScriptIncludeRegistered("keyName")) Page.ClientScript.RegisterClientScriptInclude("keyName", Page.ResolveUrl("~/Scripts/MyJavaScript.js")); 
+15
source

How to include it in ScriptManager.Scripts like this?

 <asp:ScriptManager runat="server" ID="scriptManager1" EnablePageMethods="true"> <Scripts> <asp:ScriptReference Path="~/somefile.js" /> </Scripts> </asp:ScriptManager> 

Edit:

From ascx you can do something like this (OnPreRender will be where I would try this):

 ScriptManager.GetCurrent(Page).Scripts.Add(new ScriptReference("~/somefile.js")); 

Alternatively you can try

  ScriptManager.GetCurrent(Page).RegisterClientScriptInclude( this, typeof(Page), "UniqueScriptKey", ResolveClientUrl("~/somefile.js")); 

Link Link

+2
source

Are you sure your js file is loading? Maybe the file is not in the right place - do not use ../ in the path, because it is relative and may be incorrect if you share it, and the pages are not all at the same depth:

do something like this:

 <script type="text/javascript" src="/Scripts/somefile.js" ></script> 
0
source

All Articles