Ordering Of OnLoad Scripts

ServiceNow as a platform requires particular scripts to be loaded before others to ensure that everything runs smoothly. For example, you couldn’t run a client script that references g_form if the GlideForm script hadn’t been loaded yet. It would just throw an error and crash your page load.

You might have seen this when creating a UI page and if you used the client script section to do some stuff, you probably had to wrap your code in a ServiceNow function addLoadEvent(). The sytanx is pretty well known but it goes like this:

addLoadEvent( function() {
//Custom code in the anonymous function
});

So where is this addLoadEvent function defined? It’s defined in one of ServiceNow’s core client scripts that you can see if you inspect the network/source called functions_bootstrap.js. It is actually loaded as part of one big include file for performance reasons, but you can change this behavior by changing the system property as mentioned on my article, Help With Debugging ClientSide Scripts.

When looking at this file, you will see a few other similar functions that can be used to order your onload scripts. Note: The below comments are taken straight from the file)

addTopRenderEvent (GlideForm, GlideUser defined here) - Add a function that impacts rendering of the form to the beginning of the list. used by catalog, survey, ClientScriptEmitter - make sure GlideForm is defined before all else
addRenderEvent - Add a function that impacts rendering of the form to the end of the list
addLoadEvent
addLateLoadEvent
addAfterPageLoadedEvent - Runs after the page is loaded, ready, and displayed for use

A main takeaway from this is sometimes I’ve built formatters that needed to be run very early on the page, so I’ve been able to add it to the addRenderEvent queue so that it runs before the addLoadEvent functions but after the g_form has been defined.

Also, there are some scenarios where you want to run some code that doesn’t stop the user from using the form or doesn’t directly impact them, you can add this to the addAfterPageLoadedEvent so that the form is ready to use by the user as soon as possible and not being held up by unnecessary code.

1 Comment

  1. Pingback: Preventing Form Submission Before Page Load | Service Now Gems

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s