How to ensure js is included in ascx file?

danyloid picture danyloid · Feb 17, 2011 · Viewed 14.2k times · Source

So the problem is the following :

i do have own user control. which has some javascript file in script tag included like this

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

or some javascript code directly on the ascx page. everything works if i place this control somewhere in aspx markup. but if i add this control to the page dynamically to some UpdatePanel place holder on postback (this is logic i can not alter), control renders itself and then i get js error message, which says that functions which are placed in somefile.js are not defined/are null. Why is this happening ? Is there anyway to force js including in this case.

sorry for being not enough specific but the code amount is huge and i was not able to provide a simplified example with the same error,.

The script is included but somehow the functions are not defined. I'm novice to js, so is it possible that just the script is included but not executed, so the functions are not declared ???

The interesting is that if on some page my custom control is declared in aspx. The adding some more instances dynamically causes no problem.

Answer

Jonathan Wood picture Jonathan Wood · Feb 17, 2011

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"));