OnLoad Client Script Examples: A Practical Guide for ServiceNow Developers






Mastering ServiceNow OnLoad Client Scripts: Practical Examples and Insights


Mastering ServiceNow OnLoad Client Scripts: Practical Examples and Insights

In the dynamic world of ServiceNow, user experience is paramount. How quickly and intuitively users can interact with forms directly impacts their productivity and satisfaction. This is where client scripts, particularly those that run when a form loads (OnLoad Client Scripts), play a crucial role. They allow us to dynamically shape the user interface, set initial values, enforce business logic, and guide users through complex processes right from the get-go.

While ServiceNow offers various tools for client-side customization like UI Policies, OnLoad Client Scripts provide a powerful and flexible way to implement sophisticated logic that goes beyond what UI Policies can easily achieve. This article will dive deep into practical examples of OnLoad Client Scripts, explaining their purpose, demonstrating their implementation, and offering insights into why they are so valuable in a ServiceNow implementation.

Understanding OnLoad Client Scripts

An OnLoad Client Script is a type of client-side script in ServiceNow that executes automatically when a record’s form is loaded in the browser. This means that as soon as a user opens a form (whether creating a new record or viewing an existing one), any configured OnLoad Client Scripts associated with that table will run.

The primary purpose of these scripts is to modify the form’s behavior or appearance before the user even has a chance to interact with it. Think of them as the initial setup crew for your forms, getting everything ready and in its right place.

Key functionalities often achieved with OnLoad Client Scripts include:

  • Setting default values for fields.
  • Making fields mandatory, read-only, or visible based on specific conditions.
  • Displaying informational messages or warnings.
  • Hiding or showing entire sections of a form.
  • Performing calculations or data lookups to pre-populate fields.
  • Setting the focus on a particular field.

Why Choose OnLoad Client Scripts?

You might be wondering, “Aren’t UI Policies sufficient for most of these tasks?” And yes, UI Policies are fantastic for simpler, declarative actions. However, OnLoad Client Scripts offer:

  • Advanced Logic: For complex conditional logic, calculations involving multiple fields, or interactions with other system components, client scripts offer greater programmability.
  • Performance for Complex Scenarios: While UI Policies are generally performant, in very complex scenarios with many conditions and actions, a well-written client script can sometimes be more efficient.
  • Flexibility: Client scripts allow you to execute custom JavaScript code, giving you complete control over form manipulation.
  • Interactions with APIs: You can call ServiceNow client-side APIs (like g_form) and potentially even external services (though caution is advised for performance).

Essential Client-Side APIs for OnLoad Scripts

Before we jump into examples, let’s familiarize ourselves with some critical JavaScript APIs you’ll be using extensively in your OnLoad Client Scripts. These are all part of the g_form object, which represents the form itself.

g_form.setValue(fieldName, value, displayValue)

This is your go-to for setting the value of a field. The first parameter is the internal name of the field. The second is the value you want to set. The optional third parameter, displayValue, is useful for reference fields where you want to set the displayed text (e.g., the company name) rather than just the sys_id.

g_form.setDisplayValue(fieldName, value, displayValue)

Similar to setValue, but specifically intended for fields that display a human-readable value (like dates, reference fields, etc.). It’s often a safer bet for fields where you want to ensure the display format is correct.

g_form.getValue(fieldName)

Retrieves the current value of a specified field. This is crucial for making decisions based on existing data on the form.

g_form.getDisplayBox(fieldName)

Returns the DOM element of a field. Useful for advanced DOM manipulation or getting attributes, though generally less common than setValue or getValue.

g_form.setMandatory(fieldName, mandatoryBoolean)

Controls whether a field is required. Pass true to make it mandatory, false to make it optional.

g_form.setReadOnly(fieldName, readOnlyBoolean)

Makes a field read-only (true) or editable (false).

g_form.setVisible(fieldName, visibleBoolean)

Shows (true) or hides (false) a field. This can also be used for form sections.

g_form.addInfoMessage(message)

Displays an informational message at the top of the form.

g_form.addErrorMessage(message)

Displays an error message at the top of the form.

g_user.UserID

As mentioned in the reference, this global variable provides the system ID (sys_id) of the currently logged-in user. It’s incredibly useful for user-specific logic.

Real-World OnLoad Client Script Examples

Let’s explore some practical scenarios and see how we can implement them using OnLoad Client Scripts.

Example 1: Setting Default Values Based on User or Location

Scenario: On the Incident table, when a new incident is created, we want to automatically set the “Caller” field to the currently logged-in user and, if the user is part of a specific department (e.g., “IT Support”), pre-select the “Assignment group” to “IT Help Desk.”

Table: Incident (incident)

When to run: On Load

Script:

function onLoad() {
    // Set the Caller to the current logged-in user
    g_form.setValue('caller_id', g_user.userID);

    // Get the user's department. This requires a GlideAjax call to a Script Include
    // as g_user doesn't directly expose department information.
    // For simplicity in this example, let's assume we know the user's department
    // or use a placeholder for demonstration. In a real scenario, you'd fetch this.

    // Dummy check for department - replace with actual GlideAjax call
    var userDepartment = 'IT Support'; // Replace with actual lookup

    if (userDepartment === 'IT Support') {
        // Set Assignment Group to 'IT Help Desk'
        // Note: You need the sys_id of the 'IT Help Desk' group.
        // You can find this by navigating to System Definition > Dictionary,
        // finding the 'Assignment group' field on the Incident table,
        // and looking at the 'Default value' or by inspecting the HTML source.
        // Let's assume 'sys_id_of_it_help_desk_group' is the placeholder.
        g_form.setValue('assignment_group', 'sys_id_of_it_help_desk_group');
    }

    // Another common default: if it's a specific type of incident, default the category
    var incidentType = g_form.getValue('cmdb_ci'); // Example: if a Configuration Item is selected
    if (incidentType) {
        g_form.setValue('category', 'hardware'); // Default category to 'hardware' if CI is selected
    }
}

Explanation:

  • We use g_user.userID to get the current user’s sys_id and pass it to g_form.setValue('caller_id', ...).
  • The department check is illustrative. In a real-world application, you’d typically use a Script Include and GlideAjax to securely fetch user details like department from the sys_user table.
  • g_form.setValue('assignment_group', 'sys_id_of_it_help_desk_group'); sets the assignment group. It’s critical to use the correct sys_id for the group.

Example 2: Dynamic Field Visibility Based on Incident Category

Scenario: On the Incident form, if the “Category” is set to “Software,” we want to show a “Software Type” field. If the category is “Hardware,” we want to show a “Hardware Type” field. Otherwise, both should be hidden.

Table: Incident (incident)

When to run: On Load

Script:

function onLoad() {
    // Get the current value of the category field
    var category = g_form.getValue('category');

    // Get references to the fields we want to show/hide
    var softwareTypeField = 'u_software_type'; // Replace with your custom field name
    var hardwareTypeField = 'u_hardware_type'; // Replace with your custom field name

    // First, hide both fields by default
    g_form.setVisible(softwareTypeField, false);
    g_form.setVisible(hardwareTypeField, false);

    // Now, show the appropriate field based on the category
    if (category === 'Software') {
        g_form.setVisible(softwareTypeField, true);
        // Optionally, set mandatory for the displayed field
        g_form.setMandatory(softwareTypeField, true);
    } else if (category === 'Hardware') {
        g_form.setVisible(hardwareTypeField, true);
        // Optionally, set mandatory for the displayed field
        g_form.setMandatory(hardwareTypeField, true);
    }
    // If category is neither, both remain hidden.
}

Explanation:

  • We retrieve the current value of the category field using g_form.getValue('category').
  • We then use g_form.setVisible(fieldName, false) to ensure both custom fields are hidden by default when the form loads.
  • An if-else if statement checks the category value and uses g_form.setVisible(fieldName, true) to show the relevant field.
  • We also demonstrate how to make the shown field mandatory using g_form.setMandatory().

Example 3: Displaying a Warning Message for High-Priority Incidents

Scenario: On the Incident form, if the “Impact” is set to “1 – Critical” and the “Urgency” is set to “1 – High,” display a prominent warning message to the user.

Table: Incident (incident)

When to run: On Load

Script:

function onLoad() {
    // Get Impact and Urgency values
    var impact = g_form.getValue('impact');
    var urgency = g_form.getValue('urgency');

    // Check if the conditions for a critical incident are met
    // Note: The values '1' are typical but might vary based on your instance configuration.
    // It's best to check the actual values in the dictionary or by inspecting the field.
    if (impact === '1' && urgency === '1') {
        g_form.addInfoMessage('This is a high-priority incident (Impact: Critical, Urgency: High). Please ensure it is assigned and resolved promptly.');
    }
}

Explanation:

  • We fetch the values for impact and urgency.
  • The if condition checks if both are set to ‘1’ (representing critical impact and high urgency).
  • g_form.addInfoMessage() displays a user-friendly notification at the top of the form. You could also use g_form.addErrorMessage() for more critical warnings.

Example 4: Setting a Field to Read-Only Based on Record State

Scenario: On the Change Request form, once a change request has reached the “Closed” or “Canceled” state, we want to make the “Description” field read-only to prevent further edits.

Table: Change Request (change_request)

When to run: On Load

Script:

function onLoad() {
    // Get the current state of the change request
    var state = g_form.getValue('state'); // Assuming 'state' is the field name for the change state

    // Check if the state is Closed or Canceled
    // The sys_ids for these states will depend on your configuration.
    // Common values for state might be numeric, but sys_ids are more robust.
    // For demonstration, let's assume the numeric values for simplicity.
    // In a production environment, always verify these values or use names/sys_ids.

    // Example: If state is a choice list with values like -5 (Canceled), 7 (Closed Complete), 8 (Closed Incomplete)
    var closedStates = ['7', '8']; // Example values for Closed states
    var canceledState = 'Canceled'; // Example value for Canceled state (if it's a string/name)

    // A more robust approach would be to check the display value or sys_id if known.
    // For instance, if state stores the choice value '7' for Closed Complete:
    if (state == 7 || state == 8 || state == -5) { // Example: Checking common numeric states
        g_form.setReadOnly('description', true);
        g_form.setReadOnly('short_description', true); // Example: Make short description read-only too
    }
}

Explanation:

  • We retrieve the current value of the state field.
  • The if condition checks if the state corresponds to a closed or canceled status. Important: The exact values for states can vary. It’s best to inspect the “State” field’s dictionary entry to find the correct numerical or string values, or even better, use the sys_id of the choice if you can retrieve it.
  • If the condition is met, g_form.setReadOnly('description', true) makes the description field read-only.

Example 5: Setting Form Focus on a Specific Field

Scenario: When a new “Problem” record is opened, place the cursor directly in the “Problem statement” field, ready for user input.

Table: Problem (problem)

When to run: On Load

Script:

function onLoad() {
    // Set focus to the 'problem_statement' field
    // Note: 'problem_statement' is the internal name. Verify this in your dictionary.
    g_form.focus('problem_statement');
}

Explanation:

  • The g_form.focus('fieldName') method is straightforward. It programmatically moves the cursor (sets the focus) to the specified field when the form loads. This is a simple but effective way to improve usability, especially for fields that are almost always the first thing a user needs to interact with.

Troubleshooting Common OnLoad Client Script Issues

Troubleshooting Common Issues

  • Script Not Running:
    • Check Table Association: Ensure the client script is associated with the correct table.
    • Check “On Load” Checkbox: Verify that the “On Load” option is checked in the client script record.
    • Active/Inactive Status: Make sure the client script is active.
    • Conditions: If your script has conditions, ensure they are being met.
    • Form Load Timeouts: For very complex scripts, the form might load before the script finishes, or the script might time out. Simplify the script or consider alternative approaches.
  • Field Not Updating (setValue, setVisible, etc.):
    • Internal Field Name: Double-check that you are using the correct internal name of the field. This is not always the same as the label. You can find it in the form’s dictionary entry (right-click the field label -> Configure -> Dictionary).
    • Caching: Sometimes, browser caching can cause issues. Try clearing your browser cache or accessing ServiceNow in an incognito/private window.
    • Client-Side Errors: Open your browser’s developer console (usually F12) and check for JavaScript errors. These often provide clues about what’s going wrong.
    • UI Policy Conflicts: Be aware that UI Policies can also modify field visibility, mandatory status, and read-only properties. If a UI Policy also targets the same field, its behavior might override or conflict with your client script. UI Policies run after client scripts by default, so a UI Policy could revert a change made by an OnLoad client script.
  • Performance Issues:
    • Avoid Synchronous AJAX: Never use synchronous AJAX calls in client scripts. They freeze the browser and degrade user experience. Always use asynchronous GlideAjax calls via a Script Include.
    • Minimize DOM Manipulation: While possible, excessive direct DOM manipulation can be fragile and impact performance. Stick to g_form APIs where possible.
    • Reduce `GlideRecord` Queries: If you must query data on load, do it efficiently. For server-side lookups, use GlideAjax to call a Script Include that performs the GlideRecord query.
    • Test on Different Browsers: Ensure your script behaves consistently across different browsers.
  • Incorrect State/Choice Values:
    • When checking against choice list values (like state or priority), ensure you are using the correct value (often numerical, sometimes string). Inspect the field’s dictionary entry or use g_form.getOption() to get the correct values.

Interview Relevance

Why This Matters in an Interview

Understanding and being able to implement OnLoad Client Scripts effectively is a key skill for any ServiceNow developer or administrator. Interviewers will often probe your knowledge in this area to gauge your practical ability to customize the platform.

Here’s what interviewers might look for and what you should be prepared to discuss:

  • Core Concepts: Can you explain what an OnLoad Client Script is, when it runs, and its primary purpose?
  • API Knowledge: Do you know the essential g_form APIs (setValue, getValue, setVisible, setReadOnly, setMandatory, addInfoMessage)? Can you provide examples of their usage?
  • Problem Solving: Can you walk through how you would implement a given requirement using an OnLoad Client Script? This includes breaking down the problem, identifying the necessary APIs, and writing the code.
  • Distinction from UI Policies: Can you articulate the differences between UI Policies and Client Scripts, and when you would choose one over the other? (Hint: UI Policies for declarative, simpler rules; Client Scripts for complex logic, calculations, and custom behavior).
  • Best Practices: Are you aware of best practices like avoiding synchronous AJAX, using GlideAjax for server calls, naming conventions, and the importance of checking internal field names?
  • Troubleshooting: Can you describe common issues with client scripts and how you would debug them? Mentioning browser developer consoles is a strong indicator.
  • Real-World Application: Can you provide examples from your experience where you’ve used OnLoad Client Scripts to solve a business problem or improve user experience?
  • Security and Performance: While less direct for OnLoad, understanding that client-side code is visible to the user and that performance is critical is important. Mentioning GlideAjax for server-side operations is a sign of mature understanding.

Being able to confidently explain these examples and discuss the underlying principles will significantly boost your performance in a ServiceNow technical interview.

Conclusion

OnLoad Client Scripts are a powerful tool in the ServiceNow developer’s arsenal. They enable dynamic form customization that enhances user experience, enforces business rules, and streamlines data entry right from the moment a form is accessed. By mastering the core g_form APIs and understanding common use cases, you can transform standard ServiceNow forms into intelligent, user-friendly interfaces.

Remember to always consider performance, maintainability, and potential conflicts with other customizations like UI Policies. When in doubt, consult the ServiceNow product documentation or leverage community resources. With practice and a solid understanding of these examples, you’ll be well-equipped to leverage OnLoad Client Scripts to their full potential.


Scroll to Top