I have several conferences coming up where I’ll be talking about jQuery and best practices around deployment, maintenance, and performance tuning in SharePoint and I find that I never have enough time to talk about everything I’d like. So I thought I’d write a few blogs about the subject from a complete beginners standpoint. After all, we were all beginners once and nothing frustrates me more than finding a solution to a problem, but then having no idea how to implement it.
Also, in subsequent blogs I’ll be touching on using SPServices for SharePoint 2007 and the JavaScript Client Object Model in SharePoint 2010. I’ve been avoiding using the JavaScript Client Object Model because SPServices works well in both, but you know what? Someone went to a lot of effort to write the library and I’ve heard it’s much better (actually usable) after the service pack, so this is going to be my excuse to learn it.
Yes, I realize there are several other blogs out there which cover the same topic (like Adding jQuery to SharePoint by Matthew Hughes), but I do want to give you my spin on things as well as what I have seen as best practices using jQuery in SharePoint seeing as how we use it extensively for some very high profile projects (with great success I might add). So, hopefully that gives my opinions a little credence. In other words, when I tell you to do something it’s because I went through the pains of doing it other ways first. Learn from my pain.
Have you ever noticed that my blogs tend to ramble way off topic and sound very “train of thought?”. I’ve realized that before, but just had that realization again. So, yeah, sorry about that. If you don’t like it you can get your money back for this post.
Enough already! Let’s get you fellow dummies started.
What is jQuery?
jQuery is just a JavaScript library. I highly recommend you be comfortable writing JavaScript before continuing in jQuery unless you really just want to copy and paste other people’s solutions.
You can learn more about jQuery and download the latest library from http://jquery.com
So, to use jQuery you will need to write a JavaScript script. This can be as simple as a few lines of text or it can contain thousands of lines depending on what you want to do. Whatever script you write will load/reference the jQuery library and any third party libraries you intend to utilize. The following heavily commented, but simple script displays a hello world alert after the page has loaded:
// so... first things first the "//" is called a comment (I said this blog post
// was for dummies) :)
// A comment is a line of text that is not "executed" and is generally used
// to either describe what the code is doing, or
// prevent a line of code from being executed.
// The next line of code loads the jQuery library.
// Notice it is loading it from http://aja.googleapis.com
// I don't recommend referencing these libraries externally.
// I'll explain why later
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
//indicates that the text between <script> and </script>
// is to be treated as JavaScript
<SCRIPT type=text/javascript>
//jQuery(document).ready is kind of like "main" for you old C people.
// this is the function that is executed after the page is loaded
// and everything is "ready". You may also see this as $(document).ready
// regardless, think of this as where your code starts executing.
// You don't HAVE to use this, but it's a good habit
jQuery(document).ready(function($) {
//displays the message "Hello World" on the screen.
alert("Hello World");
});
</SCRIPT>
There you go, your first jQuery script. It really doesn’t get much more simple. What we need to do now is get it to work in SharePoint.
What is SharePoint?
It’s a platform. If you don’t know what it is, then why are you reading my blog? I’m not that good of a writer.
Getting jQuery to work in SharePoint
So, again, let’s keep things simple and get the above script working in SharePoint. You have to get your script loaded into a SharePoint page somehow. Like everything else in SharePoint you have several ways of doing this. Some are good, and some are bad. Let’s discuss some of these as well as their pros and cons
The Bad Options
So, What makes these options “bad”? Many reasons actually, if you implement your scripts using the methods below you are making it cumbersome to impossible to maintain, deploy, debug, or re-use scripts. So, yes, I call that bad.
Placing script in Master Pages or directly in aspx page using SPD
I hate, hate, hate (Loathe entirely) this approach. Don’t do it. Think about it, to modify the script you have to open the page up in SPD or redeploy your MasterPage (because you do deploy your Master Pages as solutions like good boys and girls don’t you?). Well, what if you don’t have SPD access in production for some reason? Then what are you going to do?
Plus you can’t reuse the script anywhere else, and have you ever tried to edit or debug someone else’s script that has been placed directly in a page like this? Talk about a maintenance nightmare. I don’t care how easy you think it is to develop like this, don’t do it. In fact the ONLY exception I would EVER make to this rule is if you wanted to load a particular JavaScript library that is to be used by every page. I could see sticking the reference to the library in your MasterPage, otherwise, I’ll take a firm stand here and say don’t do this for any other reason.
Placing the script directly into a Content Editor Web Part
From my experience, this seems to be the most common thing people do. They edit the page, put a CEWP on the page, and paste their script into the source for the CEWP. Although this may work fine for development and playing around, there are some very good reasons not to do this in a production environment:
- First of all SharePoint 2010 tends to mangle any JavaScript using this method. At the very least it adds a lot of confusing garbage and in some cases it will render your script non-functional.
- Secondly, the script placed directly in the CEWP is not versioned in anyway, if you a user accidentally deletes the web part, the script is gone.
- Finally, you can’t reuse the script without having to maintain it in many places.
So, although I SOMETIMES utilize throwing the script into a CEWP for a quick proof of concept, I don’t leave it there and I don’t think you should either.
The Good Options
So, the following options address most of the shortcomings of the previous ones by helping make your scripts more maintainable, reusable, and deployable. How does it do this? Well, for the following options we will be putting our scripts into their own file and uploading them to a document library. So, before going any further follow these steps:
- Create a document library for your scripts (I tend to use the a library called “scripts” but 2010 has a default document library called “SiteAssets” so if you are using 2007 and want to stay consistent with 2010 call your library SiteAssets). This document library may a “central repository” for many sites or specific for a single site, just be aware of what you are doing and your reasons for doing it.
- Upload the jQuery library (and 3rd party libraries) to this document library. Again, I do not agree with referencing your jQuery libraries externally. Yes, you can make the argument that other sites do this and the user is more likely to have it cached, but what does that really gain you but a few milliseconds performance boost the first time you load the page? It is not worth the risks associated with referencing a third party library. What happens if the site where you are referencing your third party library goes down? Or you lose internet connection? or some brilliant developer changes it and breaks something? You are at the mercy of things you cannot control by referencing third party libraries externally. As a good rule of thumb, always download a local copy and put it in your scripts document library.
- Ensure your users have read access to this library and upload your scripts to this document library (if they can’t read the script, it can’t be executed).
As I previously stated by putting our scripts into the document library we get a lot of benefits. Including:
- Versioning – you can turn versioning on in your document libraries and keep older versions of your scripts around in case you need to quickly roll back.
- Metadata – Don’t upload a script named “jquery.min.1.4.2”, instead upload a script named “jquery.min” and add a field called “version” with a value of 1.4.2. This allows you to know which version you are using and allows you to upload new versions of jquery (after you have tested of course) without having to go and modify all your scripts to use the new script name. You can also use metadata to give other useful information like which pages use the script.
- Debugging/Deployment – Debugging and deployment of your scripts becomes as simple as re-uploading a script. This makes quick fixes and modifications extremely easy with little to no impact to users. You don’t like that font color? BAM… there you go… This is extremely useful for those of us who deal with those “well….. can you make that font smaller and shift everything over two pixels?” people.
At this point I should also mention that some hard core devs will insist that you deploy your scripts to the _LAYOUTS directory using a solution package. This DOES have some benefits including slight decreased load times, but I tend to find that the benefit is minimal and is not enough to consider it a best practice when taking into account all the little extras that using a document library gives you. You can argue that point though (and I know some will). It is absolutely a valid option. I just don’t want to have to deploy a solution every time Nancy changes her mind about a font color.
Okay, so now that we have our scripts in a document library (or deployed to the file system) let’s use them in our page in SharePoint!
Linking to script in a Content Editor Web Part
If you are going to use a Content Editor Web Part to get your script in a page, this is the way to go. It’s simple, fast, and easy. Essentially what you will be doing is telling your Content Editor Web Part to use and load some file instead of putting the script directly in the CEWP. In this case, the file will be your script that we previously uploaded to your document library.
In SharePoint 2007 you go to the “Modify Shared Web Part” menu of your CEWP and put the path to your script in the “Content Link” textbox.
A couple of helpful hints, ALWAYS reference your scripts using the relative path. In my screenshot up there I’m using “../SiteAssets/helloWorld.js” instead of “http://url/SiteAssets/helloWorld.js”. This makes your life much easier if you are deploying somewhere else. Also, keep in mind that when you reference the scripts in your script file and you are using a relative path there that the relative path is based upon the page that executes the script, NOT the script library itself. Make sense? In other words, your helloWorld.js script that you have uploaded to your document library should be loading the jQuery library like this:
<script src=”../SiteAssets/jquery.min.js”></script>
Instead of:
<script src=”jquery.min.js”></script>
This is of course assuming your script is in http://url/SiteAssets and the page referencing your script is at http://url/Pages/page.aspx Make sense now? The path is relative to your page.aspx and not the script itself… great. now I’m confused… just go reread this section until it make sense.
In SharePoint 2010 the process is basically identical:
So, there you go. That’s how you link your script to your Content Editor Web Part. In SharePoint 2007 you can simply click the “Apply” button and see your script in action. I’ve noticed in SharePoint 2010 you sometimes have to exit Edit mode in order to see if your script is working or not.
Using a Custom Control deployed as a solution
According to some aforementioned hardcore devs the way you should go is to create a custom control that references your JavaScript file. Now, I’m not going to go through the process of doing that here, if you REALLY want to know I can do another blog on that some other day, but not today. sorry, what can I say? I’m lazy.
This process does require more upfront effort to deploy and it needs to be deployed as a solution. In SharePoint 2010 you can do this as a sandboxed solution which makes it pretty painless and a very viable option. However, in SharePoint 2007 you must deploy this to your farm which requires being on the server and is generally more of a pain. So why would you ever do this? Well the biggest plus I see is that many people do not like giving users access to the CEWP, they don’t want them writing their own scripts or putting content into the CEWP. By using a custom control referencing a script you have much more control over those pesky users.. we can’t have them being too productive can we?
Ta Da
So, yeah.. there you go. To recap, what you need to do to start using jQuery in SharePoint is:
- Create a document library for your scripts and jQuery libraries
- Write your script, references the appropriate libraries, save it as a file and upload it to your document library
- Put a content editor web part on your page and link to the script in your document library
- Ta Da…
Again… super basic, intro stuff here. I know I need these types of posts when I really don’t even know how to get started. If you were hoping for more, stay tuned. Maybe I can turn this into a whole cool serious that I can then turn into a book which will in turn be made into a made-for-TV movie… I just hope Ricky Schroder plays the part of me.
Up Next
So… feel like you are ready for Part 2??? You can find it here:
A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields