Dynamics CRM JavaScript loading has changed drastically through the years. Currently in D365 9.x you’re able to specify the Dependent JavaScripts in the interface, and it’s supposed to asynchronously load it. Sometimes, this works great. For some reason, on some forms, and some seemingly random times, it will just not load the dependent script and you’ll get an error. I’ve not been able to replicate why it happens, but I have had to make a really obtuse workaround for the time being, and I figure I’d share it — even though it’s a bad idea and is probably a symptom of an underlying bug in the platform or our instances.
If you want to load another JavaScript using the built-in D365 jQuery, you can follow this pattern in your onLoad script on the Form Script. You can replace the “formscriptslib.js” with whichever script you’re trying to load. The “magic” is in the eval command which runs the script after $.getScript/$.ajax starts it. Otherwise it doesn’t appear to be executing at all.
//Ticket.js
function onLoad() {
var runOnLoad = function() {
console.log("put your onLoad scripts in here");
};
var loadOnLoad = function() {
if (typeof util === "undefined") {
console.log("Form Scripts FAILED to load. Loading manually.");
loadScripts(runOnLoad);
} else {
console.log("Form Scripts Loaded Correctly. Continuing to run OnLoad");
runOnLoad();
}
if (typeof util === "undefined") {
console.log("if it's still not loaded, run this script again");
setTimeout(loadOnLoad, 1000);
}
};
loadOnLoad();
}
function loadScripts(fOnLoad) {
if (typeof window.$ === 'undefined' || typeof window.$.when === 'undefined') {
window.$ = parent.$;
}
window.parent.$.ajaxSetup({
cache: true
});
window.parent.$.loadScript = function(url, callback) {
window.parent.$.ajax({
url: url,
dataType: 'script',
success: callback,
async: false //load synchronously
});
};
var urlOfScript = function(jsFile) {
var scriptElements = document.getElementsByTagName('script');
var i, element, myfile;
for (i = 0; element = scriptElements[i]; i++) {
myfile = element.src;
if (myfile.indexOf(jsFile) >= 0) {
var myurl = myfile.substring(0, myfile.indexOf(jsFile));
}
}
return myurl;
};
var directoryOfScript = function(jsFile) {
var fullUrl = urlOfScript(jsFile);
var returned = fullUrl.substring(fullUrl.indexOf('.com') + 4, fullUrl.indexOf('Form')); //set the "Form" value to whichever location you're putting scripts for Forms
console.log(returned);
return returned;
};
var formDirm = directoryOfScript('Ticket.js');
$.when(
$.getScript(formDirm + "/formscriptslib.js"),
$.Deferred(function(deferred) {
$(deferred.resolve);
})
).done(function() {
if (typeof util === "undefined") {
eval(arguments[0][0]);
}
if (fOnLoad) fOnLoad();
console.log("place your code here, the scripts are all loaded");
});
}