3

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?

1 Answer 1

5

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);
2
  • 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
    Commented Aug 25, 2011 at 12:23
  • Updated the answer with examples of both ways (acsx vs cs) Commented Aug 25, 2011 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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