How to call an external Javascript file from a webpart

Brian Roisentul picture Brian Roisentul · Feb 21, 2011 · Viewed 8k times · Source

I'm building a Web Part for SharePoint 2010 and I would like to add a simple modal.

I've registered the external js script as follows:

ScriptLink.Register(this.Page, "js/jquery-1.5.min.js", true);   
ScriptLink.Register(this.Page, "js/jquery.simplemodal-1.4.1.js", true);   

Somehow I'm getting that a message saying that the file was not found, because it's looking at 1033/_layouts directory, or something like that.

So, my question is: how could I reference an external JavaScript file from my webpart, without placing them at that directory?

Answer

markt picture markt · Feb 21, 2011

In my opinion, you should be deploying your scripts to layouts, along with images, stylesheets, etc. that are not intended to be customized by your users.

You can map the folder "Layouts" to your project in VS 2010. Then add subfolders to reflect your project name, etc. (Right click on project -> Add-> SharePoint "layouts" Mapped Folder)

Layouts
- ProjectName
- - Scripts
- - - jquery-1.5.min.js

Then, when you deploy your solution, the scripts will be copied to the proper location..

In your webpart, you can reference your scripts like:

In code:

ScriptLink.Register(this.Page, "ProjectName/Scripts/jquery-1.5.min.js", false);

But, I prefer in the .ascx:

<SharePoint:ScriptLink ID="ScriptLink2" Name="ProjectName/Scripts/jquery-1.5.min.js" runat="server" OnDemand="false" Localizable="false" />