Quick Way to Load SPServices

In a lot of the projects I work on daily, I find myself using the SPServices library (by Marc Anderson) for a lot of different types of interaction. Sometimes, I wrap up all of the functionality within a content editor web part that can be exported and potentially placed in another location of the site. jQuery is pretty much always loaded on these sites, but the SPServices library may not be loaded. Here’s a quick way to make sure that it’s available for web parts that will make use of the library.

function insureSPServices(callbackFunction) {
	if($().SPServices == null) {
		// If SPServices has not been loaded, this will return as a null value and let us know we need to load the library. The jQuery
		// getScript method runs asynchronously, so we use the callback function for initial calls to the service
		jQuery.getScript("http://sharepoint/scriptcenter/jquery/jquery.SPServices-0.5.7.min.js", callbackFunction);
	} else {
		// SPServices is already loaded, so execute our callback function which contains the rest of the page initialization.
		callbackFunction.call(null, "Already Loaded");
	}
}

function InitializePage(data, textStatus) {
	// This is the callback function called by the insureSPServices function. 
	// Here is where I would place any web-service calls that happen on the loading
	// of the page. 
	// i.e. GetDocumentLibraryTotalCount(libraryName, countContainer);
}

$(document).ready( function () {
     // when we're ready, let's make sure that SPServices is loaded.
     insureSPServices(InitializePage);
});

This will make sure that the SPServices library has been loaded before attempting to make any calls to the library.

Advertisements

3 thoughts on “Quick Way to Load SPServices

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s