CRM 2011 Polaris Asynchronous Javascript Loading

Gayan Perera, 03 March 2013

Some of you might have noticed “xyz is undefined” in your form scripts with the latest update. This is caused by the system failing to load javascript libraries in the specified order.

Let’s say you had a function that displayed a bunch of accounts.

Eg:
function DoSomething_OnLoad() {
    Example.Runner.getAccounts();
}

The above script could have relied on multiple javascript libraries to perform its operation; XrmServiceToolKit, JSON, jQuery etc etc which would have been added as form script libraries in a specific order to ensure correct dependency loading.

With the latest updated you might see “undefined errors”, to fix this you now need to control the script loading behaviour yourself rather than letting the system decide.

In order for you to do that you’ll need to use an available script loader. Two of the most popular scripts are require.js and head.js. Either one will work, but I’ve found head.js easier to implement.

I’ll show you how to implement the fix using head.js. Go over to http://headjs.com and download the latest version, it’s pretty small, under 2kb minified.

Next modify your existing “DoSomething_OnLoad” function to look like this.

function DoSomething_OnLoad() {
    // .getClientUrl() is only available RU8 and above 
    var path = Xrm.Page.context.getClientUrl() + "WebResources/<your.schema.prefix>/js/";

    var s1 = path + "script1.js";
    var s2 = path + "script2.js";
    var sN = path + "scriptN.js";

    head.js(s1, s2, sN,
        // this function gets called when all the scripts are loaded 
        function () {
            Example.Runner.getAccounts();
        });
}

Instead of directly calling “Example.Runner.getAccounts” we need to tell head.js to load all dependant scripts then call us back, at which point we can make the call to our method.

Next remove “script1, 2, N.js” from the form script libraries area, add head.js along with your bootstrapping code above.