Thursday, June 24, 2010

Dynamically load JavaScript file

Hello Gang,

Recently I needed to figure out how to load a JavaScript file into the DOM during the onload event. I was working with a form in CRM 4.0 and was tired of cutting and pasting the same .js code. Here's how I did it:

/*Load script for ajax calls*/
var scriptLoaded = false;
var TIMER= 0;

crmForm.Neudesic_LoadScript = function(scriptToLoad) {

var head= document.getElementsByTagName("head")[0];
var script= document.createElement("script");
script.type= "text/javascript";
script.src= scriptToLoad;
head.appendChild(script);
/*make sure the script gets loaded before it gets called*/
script.onreadystatechange= function () {
if (this.readyState == "complete" || this.readyState == "loaded") {
scriptLoaded = true;
}
}
}
crmForm.Neudesic_IsScriptLoaded = function() {
if(scriptLoaded) {
clearInterval (TIMER);/*this will stop the loop*/
}
return(scriptLoaded);
}

Here's the code for calling it:
if(crmForm.FormType == 1 || crmForm.FormType == 2) {
/*load script*/
crmForm.Neudesic_LoadScript("/ISV/neudesic/clarify/DCA/JavaScript/ajax.js");
/*check to see if script is loaded*/
TIMER = setInterval ("crmForm.Neudesic_IsScriptLoaded()", 500);
}
Here's a great link for more information on this topic. It covers writing some JavaScript that could do this for multiple files. Basically you need to include some arrays that hold the TIMERs and the URLs that need loaded.

Have fun,

Caleb

No comments:

Post a Comment