The CreatorCon Call for Content is officially open! Get started here.

call a client script within another client script

rody-bjerke
Giga Guru

Hi,

Is it possible to call a client script within another client script?

Let's say you have alot of code, and you want it to run OnLoad, so you create a client script OnLoad with the code.

Then you also want the same code to run OnChange when the field CI changes, then you could make 2 client scripts, one OnLoad and one OnChange with the same code. But, could you for example connect these two, so you have one client script with the code, and another client script simply just calling the first one.

Best regards,

13 REPLIES 13

deenbandhusingh
Giga Expert

Hi,

 

As mentioned above, I have my reusableFunction() in onLoad() client script and calling it from onChange() script but still it is not working. I'm getting ReferenceError: reusableFunction is not defined.

 

This concept is working fine in my one of the catalog item. I created a copy of old catalog item and now in new catalog item same thing is not working. I checked in new catalog item, both onLoad and onChange script have global scope.

Kevin163
Tera Contributor

The function should not be in the onLoad() function, but below it, IE

function onLoad() {}
function reusableFunction() {
  // Your Code
}

You should be able to call reusableFunction() from the onChange();

David165
Mega Expert

Hi

Are you in a scoped application? I had the same issue in my scoped application I'm working on. People kept telling me to the the onLoad to load my shared functions, but I was unable to get that method to work, I kept getting the ReferenceError: reusableFunction is not defined error.

If you look at the last post in this thread you'll see all the steps I had to go through to get shared code to work in my application.

Before jumping through those hoops make sure all your client scripts either sharing functions, or executing those functions, have "Isolate script" deselected. You'll have to add this to your client script form if you haven't already done so.

 

Regards

David

jamesmcwhinney
Giga Guru

Answer is here:

Reuse Client Script with Service Portal - IT Service Management - Question - ServiceNow Community

Avoiding code duplication in Catalog Client Scripts » Ruben Ferrero

 

The solution seems to be to do something like this in your onLoad (declare the shared function as an expression):

function onLoad() {
   //Usual onload stuff here.....
   
}
//This function is called within the various onChange methods
UpdateExtendedPrice = function(){
    //Run Shared code here!
};

I have tested this and it works on San Diego Service Portal.