Search

External js file in CRM

While doing a project where MS Dynamics CRM  is used a lot of customizations are performed by JavaScript.
Usually the way to it is to perform some JavaScript actions in the OnLoad of the Page.
MS Dynamics CRM has a extention point, where you can control the OnLoad of Detail Forms by entering JavaScript.

Now when you need to deploy your CRM configuration to more than one system (like we do at my project, it is sold as part of a product), you want to use a centralized Javascript file so you can change your url's etc. all in one place.
To do this (unsupported by Microsoft!) I learnt the following technique from CRM Specialists:

First technique

 
/* Jscript */


var script = document.createElement('script');
script.language = 'javascript';
script.src = '/_customscript/customscript.js';
script.onreadystatechange = OnScriptReadyState;
document.getElementsByTagName('head')[0].appendChild(script);

function OnScriptReadyState()
{
if (event.srcElement.readyState == 'complete')
{
// Perform onload script
//Doit();
}
}



The drawback with this technique is that the first time CRM loads (and every time the cache is empty) the script is not executed. Leaving the user to think the application does not work.


Second technique

 
function load_script (url)
{
var x = new ActiveXObject("Msxml2.XMLHTTP");
x.open('GET', url, false);
x.send('');
eval(x.responseText);
var s = x.responseText.split(/\n/);
//var r = /^function\s*([a-z_]+)/i;
var r = /^(?:function|var)\s*([a-zA-Z_]+)/i;
for (var i = 0; i < s.length; i++)
{
var m = r.exec(s[i]);
if (m != null)
{
window[m[1]] = eval(m[1]);
}
}
}

load_script("/_customscript/customscript.js");
//perform onload scripts


Third technique


This technique removes the overhead of the parsing of the functions and vars so will perform faster.

 
function InjectScript(scriptFile)
{
var netRequest = new ActiveXObject("Msxml2.XMLHTTP");
netRequest.open("GET", scriptFile, false);
netRequest.send(null);
eval(netRequest.responseText);
}

InjectScript('/_customscript/customscript.js');