Namespacing JScript in Dynamics CRM 2011

Roshan Mehta, 30 July 2012

I recently understood the importance of applying a namespace to functions inside JScript web resources in Microsoft Dynamics CRM 2011. We encountered an interesting scenario where a specific function existed in a web resource, but there also existed another function in another web resource with the same name. This can lead to incorrect functionality in a system because the CRM application will attempt to load the first function it finds which may not be the correct one.

CRM will warn you if it finds multiple web resources with the same name, but there is no mechanism in place to inform the user of multiple functions with the same name. For this reason, it is important to apply a namespace to functions in your web resources. To illustrate this further, let’s take a look at a simple example.

Let’s assume we have two separate JScript web resources called “script1” and “script2”. Each web resource contains a function called “doThisOnLoad” but the functions perform two different actions.

Script1

function doThisOnLoad() {
    alert("I belong to the script 1 web resource");
}

Script 2

function doThisOnLoad() {
    alert("I belong to the script 2 web resource");
} 

When we add these two functions to run onload of the Account form, we get the alert “I belong to the script 2 web resource” twice. CRM seems to think that the only function called “doThisOnLoad” belongs to the web resource that was loaded last. In our case, this is the function that belongs to “script2”.

If we swap the function calls around, we will see that the alert “I belong to the script1 web resource” will be displayed twice.

 Namespacing JScript in Dynamics CRM 2011

So how do we fix this? All we need to do is modify our functions so that they include a unique namespace so CRM can identify that they are separate functions. For example:

Script 1

var SCRIPT1 = {}; 

SCRIPT1.doThisOnLoad = function() {
    alert("I belong to the script 1 web resource");
} 

Script 2

var SCRIPT2 = {};


SCRIPT2.doThisOnLoad = function() {
    alert("I belong to the script 2 web resource");
} 

We will also need to change the event handlers on the CRM forms to include the namespace in the function call. Now when we load the Account form, we get the correct result.