How to call an external Javascript file from a webpart
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?
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" />
If you set "Localizable" attribute to "false" on the ScriptLink tag then it will omit the "1033" folder.
I'm not sure if this still works in SharePoint 2010, but here is how I did it in SharePoint 2007:
ScriptLink.Register(this.Page, "js/jquery-1.5.min.js", true);
List<string> list = (List<string>)HttpContext.Current.Items["sp-ScriptLinkValues"];
int index = list.Count - 1;
string item = list[index];
list[index] = item.Replace("/_layouts/1033/js",
"http://ajax.googleapis.com/ajax/libs/jquery/1.5");
If you add another "content editor" web part, you can place your "Include" code of the JavaScript file there with the complete file location.
精彩评论