ServiceNow client script best practices come down to three rules: run as little code in the browser as possible, never block the form waiting on the server, and pick the script type that matches the moment you need. Use onLoad to prepare the form, onChange to react to one field, and onSubmit only for fast, final validation. Get data from the server with g_scratchpad or asynchronous GlideAjax, not client-side GlideRecord, and use a UI policy when all you need is mandatory, read-only or visible logic.
The rest of this guide explains each rule with examples you can try on a development instance.
The four client script types
Client scripts live in the sys_script_client table. Open them from System Definition > Client Scripts. Each record has a table, a type, a UI type and a script.
| Type | Runs when | Typical use |
|---|---|---|
| onLoad | The form finishes loading | Set defaults, show messages, read g_scratchpad |
| onChange | A chosen field changes, and once during load | Clear or set dependent fields, fetch related data |
| onSubmit | The user saves or submits | Last check before the record goes to the server |
| onCellEdit | A cell is edited in a list | Block or confirm list edits |
Set the UI Type field deliberately. Desktop scripts do not run in Service Portal or mobile. If the form is used in the portal too, choose All and test it there.
onLoad: keep it small
Every onLoad script adds time before the user can work. A form with ten onLoad scripts that each call the server feels slow even if each call is quick.
- Combine related onLoad logic for one table into a single script where it makes sense.
- Read server data from
g_scratchpad, filled by a display business rule, instead of querying from the browser. - Do not hide or make fields mandatory in onLoad if a UI policy can do it.
A display business rule runs on the server before the form is sent, so the data arrives with the form:
// Display business rule on incident (server side)
(function executeRule(current, previous) {
var caller = current.caller_id.getRefRecord();
g_scratchpad.callerIsVip = caller.isValidRecord() && caller.getValue('vip') == '1';
})(current, previous);
// onLoad client script on incident
function onLoad() {
if (g_scratchpad.callerIsVip) {
g_form.addInfoMessage('This caller is a VIP. Follow the VIP handling process.');
}
}
No extra round trip, and the client script stays a few lines long. The business rule best practices guide covers display rules in more depth.
onChange: respect isLoading
ServiceNow calls every onChange script once while the form loads. That is why the default template starts with a guard:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
// logic for a real user change
}
Keep the guard unless you want the logic to run on load. Removing it is a common cause of fields being cleared or overwritten as soon as a record opens.
Other onChange rules:
- Compare values before acting. If
newValue === oldValue, there is nothing to do. - Avoid chains. Setting field B from an onChange on field A fires B's onChange too. Two scripts that set each other's fields can loop. Keep dependencies one way.
- Handle the empty case on purpose. The template returns when the field is cleared. If clearing field A should also clear field B, handle that before the return.
A good small example is the library script that clears the assignee when the assignment group changes.
Call the server with asynchronous GlideAjax
When an onChange needs server data, use GlideAjax with getXMLAnswer and a callback. The form stays responsive while the request runs.
The server side is a client-callable script include. Select Client callable on the script include record:
var IncidentClientUtils = Class.create();
IncidentClientUtils.prototype = Object.extendsObject(AbstractAjaxProcessor, {
isVipUser: function() {
var userId = this.getParameter('sysparm_user_id');
var user = new GlideRecordSecure('sys_user');
if (!userId || !user.get(userId)) {
return 'false';
}
return user.getValue('vip') == '1' ? 'true' : 'false';
},
type: 'IncidentClientUtils'
});
The onChange script on the caller_id field calls it:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
g_form.hideFieldMsg('caller_id');
return;
}
var ga = new GlideAjax('IncidentClientUtils');
ga.addParam('sysparm_name', 'isVipUser');
ga.addParam('sysparm_user_id', newValue);
ga.getXMLAnswer(function(answer) {
g_form.hideFieldMsg('caller_id');
if (answer === 'true') {
g_form.showFieldMsg('caller_id', 'VIP caller', 'info');
}
});
}
Points worth copying:
- The script include uses
GlideRecordSecure, so the user only gets an answer for records they can read. Anything client callable can be called by any logged-in user with crafted parameters, so validate inputs and check access. - Return a small string, not a whole record.
- One GlideAjax call can return several values as a JSON string. Parse it with
JSON.parse(answer)in the callback.
The library has a ready GlideAjax server call and a matching response handler script include.
For a single field on a referenced record, g_form.getReference('caller_id', callback) also works asynchronously. Always pass the callback. Without one, the call is synchronous and the form waits for the server.
onSubmit: fast and synchronous
An onSubmit script stops the save by returning false. It must decide right away, which creates a trap: an asynchronous GlideAjax callback runs after the function has already returned, so it cannot cancel the submit.
Work around it by doing the server lookup earlier. Fetch what you need in an onChange, keep the result on the form or in a client variable, and let onSubmit check it locally:
function onSubmit() {
var state = g_form.getValue('state');
var notes = g_form.getValue('close_notes');
if (state === '6' && notes.trim() === '') {
g_form.clearMessages();
g_form.showFieldMsg('close_notes', 'Close notes are required to resolve.', 'error');
return false;
}
return true;
}
The state value 6 is Resolved on the base incident table. Check the choice list on your instance before reusing it.
Avoid synchronous GlideAjax (getXMLWait). It freezes the browser while it waits and is not supported in Service Portal.
Remember that onSubmit is a user experience check, not a security control. List edits, imports, REST calls and scripts skip client scripts entirely. Enforce the rule on the server with a business rule or data policy as well. The library includes an example that prevents form submission when validation fails.
Keep scripts isolated and supported
- Leave Isolate script selected. New client scripts have it selected by default. It stops the script from reaching
window,documentor jQuery directly. DOM manipulation breaks on upgrades and in other interfaces. - Use g_form, g_user and g_scratchpad only. Methods like
g_form.setValue,setMandatory,setDisplay,setReadOnlyandshowFieldMsgare supported across UIs. - Pass display values to reference fields.
g_form.setValue('assigned_to', sysId, displayName)saves a server round trip to look up the display value. - Do not trust
g_user.hasRolefor security. It is fine for showing or hiding help text. Access must be enforced by ACLs.
Client script or UI policy?
| Need | Use |
|---|---|
| Make a field mandatory, read-only or hidden on a condition | UI policy |
| Set or clear a value | Client script |
| Show a message or confirm with the user | Client script |
| Call the server | Client script with GlideAjax |
| Enforce a rule for every channel | Data policy or business rule |
UI policies reverse themselves when the condition becomes false. A client script that hides a field must also show it again, which is easy to forget.
A short checklist
- Correct type, table and UI type for every script
isLoadingguard kept in onChange scripts- No client-side GlideRecord and no synchronous GlideAjax
- Server data on load comes from
g_scratchpad - GlideAjax script includes validate input and use
GlideRecordSecure - onSubmit checks are local, quick and backed by a server rule
- Isolate script left selected, no DOM access
- UI policies used for simple mandatory, read-only and visibility rules
- Tested in every interface listed in the UI type
For the server-side habits that pair with these rules, read ServiceNow coding best practices. To keep forms working after each change, add a few form tests to your ATF regression suite.