Home | Blog | Screencasts | Projects
# Thursday, September 04, 2008

Recently I posted about using JQuery in SharePoint web parts in this post I wrapped up the JCarousel plugin. Instead of requiring the JCarousel.js file to be included into the master page, I instead made the web part inject the HTML to cause the JavaScript file to be loaded.

The first step was to include the packed version of jquery.jcarousel.pack.js into my project:

 

image

 

Notice the Embedded Resource setting for the build action.

 

Now if we add the following code to our assembly.cs file:

 

[assembly: System.Web.UI.WebResource("SPImageCarousel.jquery.jcarousel.pack.js", "text/javascript")]

 

The above line now makes our embedded resource available for use in our web part which is done by the following code:

 

protected override void OnInit(EventArgs e)
{
    Page.ClientScript.RegisterClientScriptInclude("JCarousel", Page.ClientScript.GetWebResourceUrl(this.GetType(), "SPImageCarousel.jquery.jcarousel.pack.js"));
    base.OnLoad(e);
}

 

This code will ensure that the script is only added to the page once since the key "JCarousel" is the first parameter, remember that more than one web part can be added to a page at the same time, so we need to consider this as we develop our web parts. OnInit is the perfect event to call RegisterClientScriptInclude it's nice and early in the page lifecycle.

 

So hopefully you'll find this a nice and easy way to include your JavaScript resources, it does have the disadvantage of requiring a recompile to include a later version of the JavaScript file, so your mileage may vary if this is a concern.

 

Better still if your using .NET 3.5 Service Pack 1, you could make use of the CompsiteScript element of the script manager to combine the javascript files so the browser makes fewer calls to the server.

Thursday, September 04, 2008 11:52:17 AM (E. Australia Standard Time, UTC+10:00)  #    Comments [0] - Trackback
code | JQuery | Sharepoint | Work
Tracked by:
"JQueryManager - A JQuery Script Manager" (Daniels Blog) [Trackback]
"http://httpcode.com/blogs/PermaLink,guid,7e207243-02a3-4f44-accb-28db981e0f35.a... [Pingback]
Comments are closed.
Statistics
Total Posts: 134
This Year: 0
This Month: 0
This Week: 0
Comments: 20