I have a code-behind User Control (myUserControl.ascx and myUserControl.ascx.cs) that are in

ControlTemplates/MyFolder/

and, in the code of myUserControl.ascx I need to use some javascript functions that are in a file myJavascript.js that is in

ControlTemplates/MyFolder/_scripts/

and I'm trying to import using this:

<script type="text/javascript" language="javascript" src="_scripts/myJavascript.js"></script>

but this way I get a 404 not found exception. How can import this javascript to use in the myUserControl.ascx?

link|improve this question

78% accept rate
feedback

1 Answer

up vote 5 down vote accepted

I'd recommend you use the ScriptLink control instead. It allows you to inject your JavaScript code into the page header, where they script-tags belong. It also allows you to avoid multiple imports of the same file.

Also, the recommended location for script files are in the /_layouts/ folder ({SharePoint Root}/TEMPLATES/LAYOUTS)

This is how to use the control: In the .ascx:

<SharePoint:ScriptLink name="myjavascript.js" runat="server"/>

Or in the .ascx.cs file (in OnPreRender for instance):

ScriptLink.Register(this.Page, "myjavascript.js", false);
link|improve this answer
Thanks, I changed the scripts to the layouts folder. About, the ScriptLink part, the truth is I've read the link you post, but I don't understand what I have to do. It's a class I have to call from the myUserControl.ascx.cs? from myUserControl.ascx? How it works? Have you any example how use it? Thanks – user674887 Aug 25 '11 at 12:23
Updated the answer with examples of both ways (acsx vs cs) – Wictor Wilen MCA MCM MVP Aug 25 '11 at 12:49
Worked. Thanks! – user674887 Aug 25 '11 at 13:00
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.