Fixing Script Error when Navigating through a Sub-grid in Dynamics 365

Adam Murchison, 16 April 2020

On Dynamics365 Server version: 9.1.0000.14744 you may get script errors when clicking the back button when navigating to a record through a sub-grid. The error looks like this:

The script error occurs on a script that isn’t even loaded into the target form which means that there’s a conflict in the scripts running on the target form and the form you’re navigating from. This occurs due to both scripts having the same onload function names in them.

The problem:

For example, if I have a script (account.js) running on the account entity where on load a function named ‘RunOnLoad’ is run and a script (contact.js) running on contact with a function that’s run on load named ‘RunOnLoad’ also. If I’m on the Account entity, click through on a subgrid to a contact record and then click the back button to the Account form a script error appears in the contact.js file which isn’t even loaded into the Account record’s form. This shouldn’t occur and can be a confusing error.

Account.js:

RunOnLoad = function (context) { 
    showTab(context, accountTab); 
} 

Contact.js:

RunOnLoad = function (context) {
     showTab(context, contactTab);
}

Why does this occur?

This error occurs due to the browser caching scripts and poor naming functionality. E.g. When you click the back button from Contact to Account, it’s supposed to run the on load for the account but because the contact script is cached from the previous page, it’s overwriting the account onload function with the same name and it crashes.

The fix:

There are a couple of options to fix this, the best way is to use namespaces when creating JS files. The other way to fix this would be to make sure you have unique onload function names in each file which can get difficult to maintain, so namespaces are much easier. Namespaces are a great way of ensuring JavaScript files in your Dynamics 365 system have unique onload functions for each file.

“Namespace is a container for set of identifiers, functions, methods and all that. It gives a level of direction to its contents so that it will be well distinguished and organized.” - CodeProject

This sums it up perfectly, in this example in the Contact.js file and the Account.js file we can update the Javascript files to use a unique namespace for each file.

Account.js:

var ACC = ACC || {}; 

ACC.RunOnLoad = function (context) { 
    ACC.showTab(context, accountTab); 
} 

Contact.js:

var CON = CON || {}; 

CON.RunOnLoad = function (context) { 
    CON.showTab(context, contactTab); 
} 

Now that each function has a unique namespace, update the onLoad function on the form to include the namespace. Clicking the back button now, the page won’t try run the previous script as the names differ.