SharePoint Developer Team Blog
Brought to you by Microsoft teams working on SharePoint developer content, Visual Studio tools, and of course the platform itself!
Hi again, this is Anweshi Deverasetty with a new blog post. You might have read my recent blog post Working with SharePoint 2010 Themes. Next, I am going to talk to you about how we can embed and link client side scripts for Web parts in SharePoint 2010.
Scripts are blocks of code that are inserted into a Web page and are interpreted at run time. Just like a browser interprets HTML on a Web page to determine what to display, a browser also interprets scripts to determine what actions to take when an event occurs (for example, what happens when a user clicks a button on a Web page).
Client-side scripts run on the client as opposed to the server. After a Web page is downloaded to the client computer, if the browser has enabled scripts to run, all the client-side scripts will run in the browser. Although script languages are simpler than programming languages, scripts can add sophisticated logic to Web pages and increase interactivity.
You can implement client-side scripting in a Web Part in one of two ways.
You can write script in a separate file and place the file on a server running SharePoint Server 2010. The first time the script file is referenced, the file is fetched from the server and placed in the browser's cache. Subsequent references to the script file only require the script to be fetched from the browser's cache.
Advantages
In SharePoint 2010, it’s rather easy to start SharePoint and JavaScript development. You have a predefined set of SharePoint templates which will make it easier. Follow the below steps.
function Hello() { alert('Hello'); }
http://serverURL/_wpresources/VisualWebPartProject1/ 1.0.0.0__e59f6e1bd7abeada/JSScripts/Hello.js
Now, let’s see how to link this JS file in the webpart. Open VisualWebPart1.cs file and add the following code.
private const string HelloFileName = "Hello.js"; private const string HelloIncludeScriptKey = "myHelloIncludeScript"; private const string IncludeScriptFormat = @"<script language=""{0}"" src=""{1}{2}""></script>";
public VisualWebPart1() { this.PreRender += new EventHandler(VisualWebPart1_PreRender); }
private void VisualWebPart1_PreRender(object sender, System.EventArgs e) { ClientScriptManager cs = Page.ClientScript; if (!cs.IsClientScriptBlockRegistered(HelloIncludeScriptKey)) { String location = this.ClassResourcePath + "/JSScripts/"; // Create the client script block. string includeScript = String.Format(IncludeScriptFormat, "javascript", location, HelloFileName); cs.RegisterClientScriptBlock( this.GetType(), HelloIncludeScriptKey, includeScript); } }
The Page.ISClientScriptBlockRegistered and Page.RegisterClientScriptBlock methods are obsolete in Sharepoint 2010. So, use ClientScriptManager class to call these methods.
You can explicitly specify your script in a Web Part and have the script loaded only once for all instances of the same Web Part on a Web Part Page. The IsClientScriptBlockRegistered method of the System.Web.UI.ClientScriptManager class can check if the script has been loaded for the same Web Part Page.
For example, let us suppose that you have a script function called ByeBye() that you would like to add to your Web Part, VisualWebPart1. Add the following code so that the script is loaded only once for all instances of the same Web Part on the Web Part Page.
private void VisualWebPart1_PreRender(object sender, System.EventArgs e) { ClientScriptManager cs = Page.ClientScript; if (!cs.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey)) cs.RegisterClientScriptBlock( this.GetType(), ByeByeIncludeScriptKey, EmbeddedScriptFormat); }
The following example shows how you can add two client-side scripts to a Web Part, VisualWebPart1 first by linking a separate script file to the Web Part, and then by embedding the script in the Web Part.
Here are the steps that you need to follow to create a visual Web part with client side scripts.
//--------------------------------------------------------------------- // File : VisualWebPart1.cs // // Purpose : Show an example of how to include client side script to your page. // 1) Linking to a .js file // 2) Added embedded script to the page. //--------------------------------------------------------------------- using System; using System.ComponentModel; using System.Web.UI; namespace VisualWebPartProject1.VisualWebPart1 { [ToolboxItemAttribute(false)] public class VisualWebPart1 : Microsoft.SharePoint.WebPartPages.WebPart { // Visual Studio automatically update this path when you change the Visual Web Part project item. private const string _ascxPath = @"~/_CONTROLTEMPLATES/VisualWebPartProject1/ VisualWebPart1/VisualWebPart1UserControl.ascx"; // Used for the linked script file private const string HelloFileName = "Hello.js"; private const string HelloIncludeScriptKey = "myHelloIncludeScript"; private const string IncludeScriptFormat = @"<script language=""{0}"" src=""{1}{2}""></script>"; // Used for the embedded script private const string ByeByeIncludeScriptKey = "myByeByeIncludeScript"; private const string EmbeddedScriptFormat = "<script language=javascript>function ByeBye(){alert('Bye Bye'); }</script> "; // Contructor public VisualWebPart1() { this.PreRender += new EventHandler(VisualWebPart1_PreRender); } // Client script registration event private void VisualWebPart1_PreRender(object sender, System.EventArgs e) { ClientScriptManager cs = Page.ClientScript; if (!cs.IsClientScriptBlockRegistered(HelloIncludeScriptKey)) { String location = this.ClassResourcePath + "/JSScripts/"; // Create the client script block. string includeScript = String.Format(IncludeScriptFormat, "javascript", location, HelloFileName); cs.RegisterClientScriptBlock( this.GetType(), HelloIncludeScriptKey, includeScript); } if (!cs.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey)) cs.RegisterClientScriptBlock( this.GetType(), ByeByeIncludeScriptKey, EmbeddedScriptFormat); } /// <summary> /// Render this Web Part to the output parameter specified. /// </summary> /// <param name="output"> /// The HTML writer to write out to /// </param> protected override void Render(HtmlTextWriter output) { //Button which calls a function from the Included File .js output.Write( "<br><br><input class='ms-SPButton'" + " value=\'Say Hello\' type=button onclick=\"Hello();\" >"); //Button which calls a function that is embedded in the page output.Write( "<br><br><input class='ms-SPButton'" + " value=\'Say Bye Bye\' type=button onclick=\"ByeBye();\" >"); } protected override void CreateChildControls() { Control control = Page.LoadControl(_ascxPath); Controls.Add(control); } } }
Deployment in SharePoint 2010 is very easy. You need to build the solution and use the deploy option. Once deployed you will see that the Hello.JS file gets deployed to C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\wpresources\VisualWebPartProject1\1.0.0.0__e59f6e1bd7abeada\JSScripts.
Follow the below procedure to add the Web part to a Web part page.
This topic explained how to create, embed, and link client side scripts for Web parts in SharePoint 2010. For more information, see http://msdn.microsoft.com/en-us/library/dd584169(office.11).aspx to know how this can be implemented in SharePoint 2003.
Greate post. Also have a question. What would be the difference between doing it the this way vs using a content editor webpart and pointing it to a js file (in a document library or layouts on 14 hive)
Visual Web Parts require a farm solution. If you are unable to deploy a farm solution, you can build a code-only web part or use a content editor web part.
The tradeoff with using a content editor web part and pointing to a js file in a library is that files in document libraries incur a content database hit. That might not be desirable on a site that has heavy traffic. You can avoid the db hit by uploading the js to the sharepoint root, but that requires a farm solution.
Actually, you can deploy a Visual Web Part as a sandbox solution, with certain limitations. See www.toddbaginski.com/.../create-a-sandbox-compatible-visual-web-part-with-the-visual-studio-2010-sharepoint-power-tools.aspx
There would be an issue with using the "ClassResourcePath" which is not available in Sandboxed solutions. For more see here msdn.microsoft.com/.../microsoft.sharepoint.webpartpages.webpart.classresourcepath.aspx
Cheers,
C:\Marius
Great post! However, I am trying to add resources JS files, images, CSS files as embedded resources to my custom web part, I am writing in VS2010. I have set the properties of these files as "Embedded Resources", but I am not sure, what shall I do next from this. Can you please provide any idea?