Sunday, September 5, 2010

Load External JavaScript a.k.a. Dynamic JavaScript

The script below will dynamically load a JavaScript script file to a form in MSCRM 4.0 and is functioning as of RollUp 11.  You will need to add this to the onload event of the form and ensure that you have checked the checkbox for enable onload event.  Please note that this is not supported by Microsoft and may not function if you apply a future release of MSCRM or any rollup after Rollup 11 for MSCRM 4.0

//Create a variable to hold the path to the file you want to load.  In this case I am loading my Global.js file which contains a number of functions that I use on a number of my pages
var url = '/ISV/Global.js';

//Create the ActiveX object which will load the *.js file
var x = new ActiveXObject("Msxml2.XMLHTTP"); 

//Get the file and eval it
x.open('GET', url, false); x.send('');
eval(x.responseText); 

//Break the file done by line breaks
var s = x.responseText.split(/\n/); 

//Regular expression
var r = /^function\s*([a-z_]+)/i; 

//Eval each line of the returned file.  Once this is done the loaded *.js file will be available
for (var i = 0; i < s.length; i++) 
{ 
  var m = r.exec(s[i]); 
  if (m != null) {
    window[m[1]] = eval(m[1]); 
  }
}

No comments:

Post a Comment