Navigate Up
Sign In
Supporters of Developer
Web

jQuery and SharePoint

Item is currently unrated. Press SHIFT+ENTER to rate this item.1 star selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+ESCAPE to leave rating submit mode.2 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.3 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.4 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.5 stars selected. Press SHIFT+ENTER to submit. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.
jQuery and SharePoint

jQuery is a JavaScript library. It's becoming the mainstream JavaScript framework of choice across many solutions e.g. Microsoft are taking it up for SharePoint 14, even though its an open source project and they have their own Microsoft ASP.NET AJAX framework.

Getting Started with jQuery and SharePoint

Installing jQuery into your Farm

First things first you need to find a smart way to get jQuery reference into your pages. By far the neatest way is Jan Tielens Smart Tools - SmartTools.jQuerySetup_v1_2.zip. This will add the reference as a ASCX in the 12 Hive CONTROLTEMPLATES and register it as a feature with a delegate control entry. It will also add the .js library files into your 12 hive too. Simply run setup on your SharePoint farm and you're away!

Adding Your Own Scripts

If you're doing AJAX calls, you want to load the jQuery library as soon as possible so your $.ajax (and helper method) calls can start loading while the page renders.  If you're using the *AdditionalPageHead Delegate Control*you may want to move if in the master to directly under the open HEAD tag.  If you use a < SCRIPT > tag to include jQuery, place it just under the open HEAD tag.

You also want to load other scripts asynchoronously.  Always using < SCRIPT > tags will cause each script to block the next.  A better approach is to use a $.getScript() call or dynamically create the < SCRIPT > tag and append it to the HEAD.  jQuery's $.getScript() method appends a random query string parameter to the request which prevents the browser from using the cache.  For most scripts, I prefer dynamic < SCRIPT > tags because you more frequently use the cache (304 NOT MODIFIED). 

To achieve this, your second < SCRIPT > tag in the HEAD is the loader.  The loader should load JavaScript or related CSS in parallel with the remaining SharePoint script load (e.g., core.js).  Here's an example of a loader script:

&lt;script type=&quot;text&#47;javascript&quot; src=&quot;&#47;javascripts&#47;jquery.min.js&quot;&gt;&lt;&#47;script&gt;
&lt;script type=&quot;text&#47;javascript&quot;&gt;
&#47;*
 * includeScript plugin
 * Copyright (c) 2009 Paul Grenier (endusersharepoint.com)
 * Licensed under the MIT (MIT-LICENSE.txt)
 *&#47;
(function($){
	var _debug = function(msg,type){
		if (window.console && window.console.log){
			if (!type){type=&quot;log&quot;;}
			console[type](msg);
			return true;
		}
		return false;
	};
	$.fn.includeFile = function(options, callback){
		var defaults = {&quot;tag&quot;:&quot;script&quot;,
						&quot;url&quot;:&quot;&quot;,
						&quot;media&quot;:&quot;screen&quot;,
						&quot;rel&quot;:&quot;stylesheet&quot;
						},
			o = $.extend({},defaults,options),
			head = this[0],
			file = document.createElement(o.tag);
		switch (o.tag){
			case &quot;script&quot;:
				file.src = o.url;
				file.type = o.type?o.type:&quot;text&#47;javascript&quot;;
				if (o.charset){file.charset=o.charset;}
				if (o.defer){file.defer=&quot;defer&quot;;}
				break;
			case &quot;link&quot;:
				file.type = o.type?o.type:&quot;text&#47;css&quot;;
				file.rel = &quot;stylesheet&quot;;
				file.href = o.url;
				file.media = &quot;screen&quot;;
				if (o.target){file.target=o.target;}
				if (o.rev){file.rev=o.rev;}
				if (o.hreflang){file.hreflang=o.hreflang;}
				if (o.charset){file.charset=o.charset;}
				if (callback){_debug(&quot;not all browsers support callback for &lt;&quot;+o.tag+&quot;&gt;&quot;,&quot;warn&quot;);}
				break;
			default:
				_debug(&quot;unknown tag: &lt;&quot;+o.tag+&quot;&gt;&quot;,&quot;error&quot;);
				return $(this);
		}
 		file.onload = file.onreadystatechange = function(){
			if (!this.readyState || this.readyState == &quot;loaded&quot; || this.readyState == &quot;complete&quot;){
				if (callback && typeof callback==&quot;function&quot;){callback(o);}
				file.onload = file.onreadystatechange = null;
			}
		};
		head.appendChild(file); &#47;&#47;using the jQuery object and append methods force an xhr
		return $(this);
	};
})(jQuery);
&#47;&#47;end plugin

&#47;&#47;start instructions
$(&quot;head:first&quot;)
.includeFile({&quot;url&quot;:&quot;/javascripts/accordion-nav.js&quot;},function(){
	$(&quot;head:first&quot;).includeFile({&quot;tag&quot;:&quot;link&quot;,&quot;url&quot;:&quot;/javascripts/leftnav.css&quot;}); //load the css file as a callback so it degrades
})
.includeFile({&quot;url&quot;:&quot;/javascripts/expand-collapse-all.js&quot;}) //another call chained from the first
.includeFile({&quot;url&quot;:&quot;/javascripts/ows.js&quot;}); //end with semi-colon

//end instructions
&lt;/script&gt;

Another benefit of this pattern is that Firebug can see all of these scripts and classes (not always possible with AJAX loads using the $.getScript or similar methods.

However, seeing a returned 304 NOT MODIFIED means that the browser is still requesting the file every time.  For further performance gain, you can edit the web.config to return "cacheable" in the response headers for certain file types.  This will eliminate the 304 NOT MODIFIED message because the browser does not make a new request.  See Optimization, BLOB caching and HTTP 304s

Debugging jQuery and SharePoint

By far the most recommended approach is a tool called FireBug. This allows you to debug your script and also jump into breakpoints and have a console window very much like the immediate window in the Visual Studio IDE.
This is a great article on how to use FireBug with jQuery. Essentially if you don't find you are hitting any breakpoints you can add to your javascript code to force it

debugger;

If you want to debug with browsers other than FireFox, then you can use the Jquery Debugger Plugin to log values directly onto the page itself into a DIV that you mark with an ID of "DEBUG". It's not as nice as FireBug, but it works across browsers.

Selecting elements on SharePoint ASPX pages with jQuery

If you're looking at jQuery in SharePoint, $("#...") selector will only return first element because IDs should be unique (however, SP often renders multiple elements with the same ID) and also because of issues with special characters, use $("[id='...']") instead e.g. $("[id='foobar']") instead of $("#foobar").

Finding stuff in the jQuery API

@Autosponge referred me to a great tool called the jQuery API which is an Adobe AIR app to find all the methods!

Using the Google AJAX Libraries API to load jQuery

jQuery can also be loaded from the Google web servers into SharePoint. This method brings the following advantages:

  • Reduced bandwidth usage on your server.
  • Browsers only allow a certain number of connections to the same server, so this allows another connection to be opened in parallel.
  • User's browser cache may already contain the jQuery JavaScript file thanks to other sites using the Google API.
  • No need to manage deployment of the jQuery JavaScript files and version can be switched easily.
  • The file is downloaded from the user's nearest geographical location.

To use the API replace your existing reference to jQuery with the following:

&lt;script type=&quot;text&#47;javascript&quot; src=&quot;http:&#47;&#47;www.google.com&#47;jsapi&quot;&gt;&lt;&#47;script&gt;
&lt;script type=&quot;text&#47;javascript&quot;&gt;
	google.load(&quot;jquery&quot;, &quot;1.3.2&quot;);
&lt;&#47;script&gt;

See more on the AJAX Libraries API site.

External References

Categories:
No categories were selected

Comments

Mike Hansford

Re: jQuery and SharePoint

I've found one of the main culprits of SharePoint producing multiple elements with the same ID is the RSS Viewer Web Part. However, this has been mainly a result of a poorly formed RSS file to begin with. I've come across several sites that put content inside CDATA sections in the element of the RSS file. Inside the CDATA sections are DIV tags with an ID attribute. These attributes are repeated from one entry to another. This is what has caused the invalid HTML markup.

Interestingly, I've also found that Firefox just parses the whole document and finds all the DIV tags. IE takes the view that the rules are the rules and that an ID tag will be unique.

Posted 28-Apr-2009 by Mike Hansford

Re: jQuery and SharePoint

Thanks for the post. Here is a simple blog post about integrating JQuery in SharePoint on a simple page. Hope this helps people who are new to SharePoint.

http:&#47;&#47;praveenbattula.blogspot.com&#47;2009&#47;05&#47;jquery-integration-in-sharepoint.html

Posted 05-Jun-2009 by
Paul Grenier

Re: jQuery and SharePoint

That approach is fine for testing, but if you stick with it you'll run into a few problems.

First, you'll have multiple copies of jQuery in the environment.  As a result, users will not cache or used a cached copy (that's the whole reason to use Google's version if you can).

Second, Once you bind jQuery to the single page in a script tag, you can't add it to the master.  If you do, and let's say, the .master has a newer version, the one on the page will overwrite it.  It should be done with a lazy load method in a single page, NOT a script tag.

Third, with different versions of jQuery on the site, you can't add ANY custom scripts to the .master because unit testing is a train wreck.  Everything becomes a one-off.

I highly recommend working with a single version of jQuery and putting it everywhere (i.e., the .master).  Second to that, use a local version of jQuery called jquery-latest.js or something, and pointing all of your pages to that version using a lazy load method.  That way, if you later add it to a .master, nothing breaks and it doesn't try to load twice or load different versions.  Lastly, when you make a change to your jQuery version, test all of your scripts--this is especially important for SP because our audience is largely IE and IE always seems to log more bugs than other browsers (and they're not all found before a new version releases e.g., the :visible bug).

Posted 05-Jun-2009 by Paul Grenier
Christophe Humbert

Re: jQuery and SharePoint

You can also call the jQuery script directly from the Google or Microsoft CDN, without having to load the Google API.

@Paul: in practice having a single version of jQuery is not realistic when you rely on third party plugins. You'll come across very useful plugins that are not regularly maintained, and will only work with specific versions of jQuery (or be upgraded with a delay). I have even seen articles that explain how to manage multiple versions of jQuery in the same Web page.

Posted 05-Nov-2009 by Christophe Humbert

Notify me of comments to this article

E-mail:
   

Add Comment

Title:

 
Comment:
Email:

   


Name:

 
Url: