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

i have written 2 client scrpits

17911a03e8
Kilo Contributor

1 st client script is onload test

function onLoad() {
   //Type appropriate comment here, and begin script below
   if (!g_user.hasRole('admin')){
g_form.setVisible('contact_type', false);
g_form.addInfoMessage('hello non admin');
   }
}
--------------------------------------------------------------------
2nd client script is 
function onLoad() {
   //Type appropriate comment here, and begin script below
   if (g_scratchpad.isVIP) {
        g_form.addInfoMessage("⚠️ Caller is a VIP! Handle with high priority.");
   
}
---------------------------------------------------------------------------------------------------
if i want to execute the onload test script it is executed when i make the 2nd script (active as false)the only onload test is working.Can someone explain me why?
4 REPLIES 4

Laveena-Agarwal
Kilo Sage

Hi @17911a03e8 

There could be several reasons for the conflict:

  1. Both client scripts have the same execution order.

  2. The second client script uses the scratchpad, which triggers a Display Business Rule to run before the onLoad client scripts execute.

Best practice: Consolidate the logic into a single onLoad client script. Having multiple onLoad scripts can increase processing time and negatively impact the user experience.

Bhuvan
Mega Patron

@17911a03e8 

 

Dot walk on user field and check if it is VIP user as your client script 2 is not checking correctly.

 

Where possible, merge client scripts and do not have multiple client scripts for same condition [in your case onLoad]

 

Follow below best practices

 

https://developer.servicenow.com/dev.do#!/guides/xanadu/now-platform/tpb-guide/client_scripting_tech...

 

If my response helped to guide you or answer your query, please mark it helpful & accept the solution.

 

Thanks,

Bhuvan

Anand Kumar P
Giga Patron

Hi @17911a03e8 ,

 

Check your scratchpad variable returning any value if value not defined it will not execute.

if (g_scratchpad.yourVariableName !== undefined) {
// The scratchpad variable is defined.
} else {
// The scratchpad variable is undefined.
}

 

If my response helped, please mark it as the accepted solution and give a thumbs up👍.
Thanks,
Anand

 

Rafael Batistot
Kilo Patron

Hi @17911a03e8 

 

Both your client scripts use function onLoad().
In JavaScript, if two functions have the same name, the last one loaded overwrites the first. That’s why only one script executes.

 

Why disabling works: With only one active, there’s no overwrite, so it runs fine.

Fix:

    • Don’t reuse the same function name.
    • Either give them unique names (onLoadAdminCheck, onLoadVIPCheck), or just keep the ServiceNow default onLoad(control, oldValue, newValue, isLoading, isTemplate) signature.
    • That way, ServiceNow will load and run each script independently.