The is the first of a four-part series of blog posts that describe the JavaScript client object model also known as JSOM. They describe how JSOM works and what files are required for loading JSOM scripts. It also provides a walkthrough of various access and data manipulation operations that can be performed using JSOM.

About the ECMA Script Object Model also Known as JSOM

SharePoint developers have been limited to coding on the server-side since SharePoint’s inception. SharePoint 2007 provides developers with a robust server-side API that allows for the manipulation of virtually any object in the platform. However, support for accessing SharePoint data from the client is limited to the use of various Web services. The Web services do provide access to the object model but their scope is limited and developers have to either constrain their goals or rely on external API’s, such as JQuery, when dealing with scenarios such as the manipulation of SharePoint data after a page has been loaded.

SharePoint 2010 improves this scenario by providing a subset of the familiar server-side object model to the client by using the SharePoint 2010 Client Object Model. The client object model is targeted towards building client-side applications by using WPF/Windows or Microsoft Silverlight and for hosting client side code by using JavaScript.

Note: For information regarding other client object model approaches, see the posts written by Steve Peschka at (http://blogs.technet.com/b/speschka/archive/2009/11/01/using-the-sharepoint-2010-client-object-model-part-1.aspx.

JSOM is intended for accessing and manipulating SharePoint objects by using JavaScript (ECMAScript) in an asynchronous fashion. It is very useful in situations where you want to access SharePoint data or make manipulations to the data after the page has been loaded on the client.

JSOM is made up from a set of JavaScript files and can be easily used in any Page or Web Part by simply referring to JSOM scripts. In some cases, you may not need to provide any references such as in the case of a page referencing the standard SharePoint 2010 master pages.

As an example, you can use an editor such as a content editor Web Part to access and manipulate SharePoint objects by using JSOM. For instance, SharePoint 2010 uses JSOM extensively for its own usage; an example of this is the new modal dialog introduced in SharePoint 2010. This modal dialog is actually a part of the client-side SP.UI namespace and leverages JSOM to perform common operations.

JSOM provides a comprehensive set of APIs that can be used to perform operations on most

SharePoint objects such as Site, Web, List, ContentTypes, User Permission and so forth. The API is simple to use and allows the developer to focus on the business scenario with a minimum amount of infrastructure required. JSOM fully supports JQuery and both can be used in conjunction with the other.

When using JSOM it is important to note that JSOM can only be used with SharePoint sites and not just any website; for example, making a call from an ASP.NET site to access SharePoint objects is prohibited. Additionally, making a call from one SharePoint site to another is not allowed because both of these scenarios would result in cross-site scripting. Also, JSOM currently only supports the following browser versions. Other browsers may be supported but have not been tested.

  • Microsoft Internet Explorer 7.0 or greater
  • Firefox 3.5 or greater
  • Safari 4.0 and greater

Developing with JSOM is similar to using any other object model with some minor syntactical differences. However, before getting into writing code by using JSOM, it is important to understand how it actually works:

The following is a graphical representation of what happens when a page is accessed in a client browser.

Figure1

The client browser initiates an HttpRequest to the server. The server tries to load the page and starts preparing the master page. If the master page is the standard SharePoint Foundation master page, it already contains references to the required JSOM scripts; if a custom master page is used then you must add the relevant JSOM references before the pages and controls can use the JSOM. SharePoint then identifies the files that need to be sent to the client from the {SharePointRoot}\TEMPLATE\LAYOUTS directory and returns a response that downloads all the files to the host computer.

  • SP.js
  • SP.Core.js
  • SP.Runtime.js

These files are smaller versions of the JavaScript files and depending on the working environment; you might have the debug versions of these files downloaded to your client (more on this in future posts).

This is similar to what happens in SharePoint 2007 with some differences. When a request is made to access a page, only the files required to render the page are downloaded to the client. For example, if your programs use only the SP.CORE.js script, you can specify that only this script is downloaded to the client. This is a huge performance boost from earlier version of SharePoint which downloaded the complete set of core JavaScript files when a page was accessed. If the script has references to any other files, they are also automatically downloaded to the client.

How does SharePoint ensure that only the required files are downloaded to the client machine? What about identifying and downloading the dependencies between files? The answer is the SharePoint 2010 Script on Demand (SOD) framework. SOD ensures that only the required files are downloaded to the client and provides options to load them in the background after the page has completed loading. SOD is a class defined in the init.js file and contains methods for loading scripts, registering script dependencies, executing methods within a loaded page, and event notification. You use SOD to load the OOB SharePoint js files and your own JavaScript files.

SharePoint provides multiple ways to enable on-demand loading of scripts:

  • The easiest way to enable on-demand loading is to set the OnDemand="true" attribute for the SharePoint:ScriptLink server tag when referencing a required JavaScript file.

Setting the OnDemand attribute to true, instructs the framework to register the script for "on demand loading" by rendering something such as this:

<script type="text/javascript">

SP.SOD.RegisterSod("SP.js", "\_layouts\SP.js");

</script>

  • You can also directly call the SP.SOD.registerSod method defined in the SP.SOD class of the init.js file from your custom Javascript files; this will register the script to be loaded on demand. You can then call the SP.SOD.execute(key, functionName, args) method or the SP.SOD.executeOrDelayUntilScriptLoaded(func, depScriptFileName) method to load the script and execute its methods.

Note: Dallas Tester has a blog post that describes more about the API in SP.SOD (http://blogs.msdn.com/b/sharepointdev/archive/2011/01/27/loading-script-in-sharepoint-2010.aspx).

  • If you want to register a script from within a Web Part, you can call the ScriptLink.RegisterOnDemand(page, strFile, localizable) method from the OnPreRender () event of your code to register the custom script.

After the object model is downloaded, you can make calls to perform operations in SharePoint. Any JSOM operation results in an Xml request and SharePoint returns a JSON response to it as shown in the following figure.

Figure2

The following example can help you to understand the request/response model. The following code snippet uses JSOM to retrieve an item based on its ID. It returns the current client context and then calls the executeQueryASync method, specifying the callback methods for success and failure of the operation.

var item;

Function getItemById(itemId)

{

var clientContext = new SP.ClientContext.get_current();

var web = clientContext.get_web();

var list = web.get_lists().getByTitle('mycustomList');

This.item = list.getItemById(itemId);

clientContext.load(item);

clientContext.executeQueryASync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailure);

}

Function onSuccess()

{

Alert('Success');

}

Function onFailure()

{

Alert('Failure!');

}

When the getItemById method is executed, an XmlRequest object is created and sent to SharePoint for processing. The client object model acts as a proxy to connect to a WCF service (Client.svc) for the processing of the request. The Client.svc service is the protocol server responsible for performing all of the operations requested by the client object model. The service is located at /_vti_bin/client.svc on the server. The protocol server endpoint appends /_vti_bin/client.svc/ProcessQuery to process a request and requires a formatted Xml Request message based on the client protocol specifications.

Note: The client protocol specifications are two protocols defined under the SharePoint Open Specification standards the allow the execution of a client side operation:

  • SharePoint Client side object modal Protocol [MS-CSOMSPT]
  • SharePoint Client Query Protocol [MS-CSOM]

These protocols define the types, relationships, message formats, exceptions, transport channels, security considerations required by any request/response when accessing the client object model. The following is a stack of protocol client and industry standards defined in the SharePoint CSOM Open Specifications used to execute any operation using the client object model.

Figure3

A typical XmlRequest message might look like this:

<Request 

  AddExpandoFieldTypeSuffix="true" 

  SchemaVersion="14.0.0.0" 

  LibraryVersion="14.0.4006.3001" 

  ApplicationName=".NET Library" 

  xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009">

  <Actions>

    <ObjectPath Id="2" ObjectPathId="1" />

    <ObjectPath Id="4" ObjectPathId="3" />

    <ObjectPath Id="6" ObjectPathId="5" />

    <Query Id="7" ObjectPathId="5">

      <Query SelectAllProperties="true">

        <Properties />

      </Query>

    </Query>

    <ObjectPath Id="9" ObjectPathId="8" />

    <Query Id="10" ObjectPathId="8">

      <Query SelectAllProperties="false">

        <Properties>

          <Property Name="Author" ScalarProperty="true" />

          <Property Name="Status" ScalarProperty="true" />

        </Properties>

      </Query>

    </Query>

  </Actions>

  <ObjectPaths>

    <StaticProperty Id="1" TypeId="{acc57e47-24b0-4400-b1c7-aa1cf3c9542d}" 

     Name="Catalog" />

    <Property Id="3" ParentId="1" Name="Books" />

    <Method Id="5" ParentId="3" Name="GetById">

      <Parameters>

        <Parameter Type="Guid">{3387ac63-e73d-421f-bff7-359a4aa2bc38}

        </Parameter>

      </Parameters>

    </Method>

    <Method Id="8" ParentId="3" Name="GetById">

      <Parameters>

        <Parameter Type="Guid">{704655a3-c136-469c-a578-f79652a93f9b}

        </Parameter>

      </Parameters>

    </Method>

  </ObjectPaths>

               </Request>

Client.svc is an internal WCF service; it is reserved for SharePoint usage and is not intended to be used directly in client code. If you attempt to add a service reference to this service, no proxy will be generated. Internally, the Client.svc leverages the server-side object model to handle all client requests and return a JSON response.

A typical JSON response might look similar to the following:

[

  {

    "SchemaVersion" : "14.0.0.0",

    "LibraryVersion" : "14.0.4006.3001",

    "ErrorInfo" : null

  },

  2,

  {

    "IsNull" : false

  },

  4,

  { 

105 / 134

[MS-CSOM] — v20110315  

 SharePoint Client Query Protocol Specification 

 

 Copyright © 2011 Microsoft Corporation. 

 

 Release: Tuesday, March 15, 2011 

    "IsNull" : false

  },

  6,

  {

    "IsNull" : false

  },

  7,

  {

    "_ObjectType_" : "SampleCode.Book",

    "Id" : "\/Guid(3387ac63-e73d-421f-bff7-359a4aa2bc38)\/",

    "Author" : "John Arthur",

    "Title" : "How to Cook Chinese Food",

    "Status" : 0,

    "PublishDate" : "\/Date(2008,2,1,0,0,0,0)\/"

  },

  9,

  {

    "IsNull" : false

  },

  10,

  {

    "_ObjectType_" : "SampleCode.Book",

    "Author" : "Jim Bates",

    "Status" : 0

  }

]

This post provides an overview of how the ECMAScript client object model works. The next post describes how to make your pages and Web Parts ready to use JSOM and how to work with JSOM in Visual Studio 2010.