Microsoft’s CRM tool offers some pretty powerful JavaScript event hooks. One thing it doesn’t appear to offer, however, is a way to import a library of JS functions and re-use them across different event handlers.

For example, if one wanted to display a “Hello, world!” message whenever several different attributes were changed, the conventional approach would be to embed the call to alert() in each of the event handlers. Obviously, for such a simple example, this isn’t such a big deal, but for more sophisticated logic it becomes unwieldy very, very rapidly.

One common approach is to use externally-referenced script files. Great, but imagine the horror when you suddenly discover that your system administrator has been religiously backing up your CRM server for the last six years, but hasn’t backed up the web server from which you were serving your scripts… We still have the problem of how to reference them, too.

Variable declarations in JavaScript (evilly) default to global. What you can do to exploit this, however, is to declare a global function pointer from within an OnLoad event handler as follows:

// This is the OnLoad event handler provided by CRM
function OnLoad() {
    // This is the function that we want to make
    // available globally.
    window.helloWorldFunction = function() {
        alert("Hello, world!");
    }
}

Then, in your event handler for other controls on the page, you can re-use that global variable:

// This is the OnChange event handler provided by CRM
function OnChange() {
    // ... and here's the one we prepared earlier.
    helloWorldFunction();
}