A jQuery Primer for SharePoint

This entry is part 1 of 4 in the series A jQuery Primer for SharePoint

There’s no shortage of articles available on the Web about using jQuery with SharePoint. In fact, I’ve written a lot of them myself on my blog and for other websites. However, most of the articles you’ll find tell you about how to tackle one specific problem and may give you some code snippets to do so. What I’d like to do here is give you a decent overview of what jQuery is and what it’s useful for doing in SharePoint.

jQuery is absolutely one of the hot, new exciting things available to create functionality for the Web.  In that sense, it’s the latest shiny penny everyone wants to pick up and play with. There are also some times when jQuery is not such a great idea, and I’ll try to give you some simple questions to ask yourself the next time you feel like jQuery is the answer.

What Is jQuery?

From the home page of jQuery.com:

jQuery Primer for SharePoint - Figure 1

Even more simply, jQuery is simply JavaScript. If you’ve ever done any development in JavaScript (or any other language for that matter), you’ve likely created some reusable functions. jQuery is a large set of reusable JavaScript functions that let you accomplish things more easily and quickly than by writing plain JavaScript. There’s really nothing in jQuery that you couldn’t write in JavaScript yourself if you had the time and the skills.

jQuery was created by a very smart gentleman named John Resig, way back in the dark ages of 2005.

If you’re interested in some of the milestones for jQuery, check out the History page at the jQuery Project.

Since John’s original work, jQuery has really taken the web development community by storm, showing up in everything from major public-facing sites to small side projects. Hundreds, if not thousands of “jQuery plug-ins” have been created by anyone, from individuals to large companies (including Microsoft), and many are available for free download on the Web. I’ve written my own “plug-in,” or library, that works with jQuery and SharePoint’s web services. I initially called it the jQuery Library for SharePoint Web Services, but generally we all call it SPServices these days.

JavaScript generally runs in the browser. All modern browsers include a JavaScript engine that will interpret and run the script. Most of these engines act the same, but there are also some differences that can be very subtle or even more nefarious. jQuery is great because it “smooths over” these differences. One of the primary goals for jQuery is the old “write once, use anywhere” mantra. In jQuery’s case, though, the execution level is extremely good. So, unlike some other promises of this sort of ubiquity, jQuery does it very well.

What Can jQuery Do for Me?

Everyone talks about how cool jQuery is, but what can it actually do for you? jQuery lets you do many things, but here’s a list of some of the most useful:

  • Find elements in the Document Object Model (DOM) and manipulate them. This manipulation might include changing values, attributes, or CSS styles.
  • Attach to and act on user-driven events.
  • Get data dynamically from other locations using Ajax for use in the page in the browser.

These seemingly simple capabilities can add up to pretty amazing things like fully animated pages a la Flash, the reading and writing of SharePoint list data, and highly interactive web pages.

So, what types of things are you able to accomplish? Well, you can make the page more “active,” meaning that it can respond more rapidly to user actions. You can do validations across columns in forms, make the forms easier to use, and ensure better quality data. You can cross-reference external data sources with web services. You can animate things in the page. There’s really a wide assortment of possibilities.

Getting jQuery

jQuery Primer for SharePoint - Figure 2

The first thing you need to do to use jQuery is download it from the jQuery website. jQuery is free and dual licensed under the MIT or GPL Version 2 licenses. These two licenses are among the least restrictive for open source software distribution. Unless your lawyers get wind of you using the code, you may never care, but what these licenses basically say is that you can do anything you’d like with with jQuery, commercially or otherwise, as long as you keep the licensing language intact in the header of the code.

There are two options for download: the Production version (26KB, minified and gzipped) and the Development version (179KB, uncompressed code).

These statistics are for the current version, which is 1.4.4 as of this writing.

I’ll talk a little more about minification in a bit, but the wording here is pretty clear. Use the Production version in production environments and the development version in development environments, but really only if you will want to debug issues or errors that might be thrown in jQuery itself.

Referencing jQuery and Other Plug-ins

There are different ways you can use, or reference, jQuery and other plug-ins in your applications. The quickest way is to simply include a script tag that points to the .js file for its source.

<script src="/jQuery%20Libraries/jquery-1.4.4.min.js" type="text/javascript"><!--mce:0--></script>

In this example, I’ve stored the jQuery file jquery-1.4.4.min.js in a Document Library in the root site of my Site Collection called jQuery Libraries. That’s all there is to it; now jQuery is available for me to use. I can make that reference in one specific page, in a page layout, or even in the master page.

You should make your decision on this based on how pervasively you expect to use jQuery. I’m seeing that more and more people are simply including the reference to jQuery in the master page. This makes it manageable in one single place for the entire site collection (assuming you are using a single master page) and easily upgraded when a new version of jQuery is released.

You can, of course, store the jQuery file in the file system (almost always somewhere in _layouts) on your Web Front Ends (WFEs) if you’d like to deploy the file as part of a solution package (WSP). You can store the file anywhere that is accessible via HTTP.

If your users’ browsers can access the Internet, you might also want to consider referencing jQuery from one of the publically available content delivery networks (CDNs). The benefit of this approach is that the user’s browser cache may well already contain the file (since so many other sites are using jQuery), and you can reduce some of the demand on IIS in your own farm. The CDNs that are available for jQuery are listed on the jQuery site. Most people use either Microsoft’s CDN or Google’s CDN.

Some of the right choices for deployment and referencing should, of course, be driven by your governance model.

Minification

Minification is sort of like compilation for script. By running a minification engine on your jQuery code, you end up with a “squished” version that has all of the comments and white space stripped out. Minification also shortens variable names and optimizes the script as much as possible. What this does for you is provide the smallest possible footprint for your script, minimizing the number of bytes required to download to your browser.

The other important benefit is the the script may be interpreted more quickly as it is loaded by your browser.

I like to use  the JavaScript CompressorRater to do my minification for SPServices because it passes my script through all the major minification engines, allowing me to compare and contrast the results and decide which is the right one for me to use.

To illustrate how minification works, here’s a trivial example. All this does is find the Search box in the page in WSS 3.0 and prepopulate it with the text “Type your search term here” once the page is fully loaded. This could become a part of a helpful “ghost text” prompt for the column.

$(document).ready(function() {
  $("input[Name='SearchString']").val("Type your search term here");
});

Passing this script through the JavaScript CompressoRator, the smallest result returned is from the YUI Compressor 2.4.2 (no options):

$(document).ready(function(){$("input[Name='SearchString']").val("Type your search term here")});

As you can see, the script is still totally legible. All that the YUI Compressor has really done here is remove the whitespace because the script is so simple.

Contrast the output from the YUI Compressor with what I get back from Packer 3.1 (options: shrink, base62, privateVars):

eval(function(p,a,c,k,e,r){e=String;if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'^$'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('$(document).ready(function(){$("input[Name=\'SearchString\']").val("Type your search term here")});',[],1,''.split('|'),0,{}))

The “compression” in this case actually makes the script more than three times as large.

The point of this little exercise is that there are quite a few different approaches to compression, and they aren’t all optimal for all code. It’s good to compare the results from several methods to see what is best for your specific code. I’d suggest the you try copying the previous script (or any other script you may have) and pasting it into the JavaScript CompressoRator yourself, just to see how it works. The JavaScript CompressoRator page also has links to look at how the different compression schemes work for some popular libraries, with jQuery 1.3.2 among them.

The other thing that minification does is to potentially optimize the script for execution, not just download. By reducing the length of variable names, packing the code tightly, and possible replacing functions with more efficient script, your code *may* run more quickly in the browser. This benefit is more difficult to measure but may be a consideration for you if you are using jQuery heavily. In most cases, though, using jQuery in SharePoint probably won’t require this benefit; I’d expect it would be most important in applications that are almost entirely script-based.

There’s one other note about compression that is important to mention. Most modern browsers also will gzip files. This is sort of like running WinZip on the files in real time as they are downloaded. That’s why the actual number of bytes sent down the line is usually fewer than the actual file size.

When Is Using jQuery a Bad Idea?

To restate, jQuery is script that runs in the browser. One of the key things you need to understand is what your user base is using, not just for browsers but also what type of hardware and software they have. This isn’t any different from developing other types of software: you must understand the worst case and usually the median case.

You’ll undoubtedly want your script run in the worst case and run fairly well. There are still many corporate environments out there where the standard browser is Internet Explorer 6 and the operation system is Windows XP. jQuery will run in those instances, but there are some special considerations you’ll need to make.

Another thing that sometimes happens is that, because jQuery is hot, everyone wants to use it. There are many things that should still be done on the server, not the client. Examples would be heavy data manipulation, handling large data sets, and applications that must be extremely secure. It’s not that you can’t do these things when you use script; it’s that there are special considerations again.

I’m a huge fan of using SharePoint’s web services with jQuery, and I wrote SPServices because of it. But there are many things you can’t or shouldn’t do with the web services. Again, there are a lot of circumstances where heavy processing ought to happen on the server, not on the client. You also can’t elevate permissions from the client without passing credentials in the clear, which is a big no-no.

So, consider your governance model and think about what the right architecture is based on your specific application requirements.

What’s Next?

Once you understand the concepts covered and have a reference to jQuery, you’re off and running. This article was meant just to help you understand what jQuery is and how you can get started. In future articles, I’ll talk about some of the specific things you can accomplish with jQuery and SharePoint.

Series NavigationA jQuery Primer for SharePoint: Selectors, Attributes, and Traversing – Oh My!
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!

Leave a Reply

Before you post, please prove you are sentient.

What is frozen water?