logo

NJP

Create a Script Element on a UI Page Using Jelly (cache busting)

Import · May 10, 2017 · article

Create a Script Element on a UI Page with Jelly to ensure the latest version of the script is loaded (cache busting)

Problem

I am trying to address the following problem with this post.

You have a UI Page or UI Macro that relies on a UI Script and you want to ensure that the latest version of the UI script is loaded.

For example I have a page that loads a script license_page_angular_app, so I have created the following script block.

The first time I load the page in the browser everything works fine.

However, if I make an update to the script, the script changes don't have any effect. This is because the first version of the script has been cached in the browser.

To get the browser to download the new version of the script, I need to make the src URL for the script block different. To do this, I add a query string to the URL with a version value, for example by making the src value license_page_angular_app.jsdbx?v=5 as in the script value below.

?v=5">

This works. However, it means that each time I update the script I need to update the src value on all elements that load the script.</p> <h3>Solution</h3> <p>I am using the following method to solve this problem:</p> <p>Instead of using static html for the script element, I use Jelly to create the script element.</p> <p>To ensure that the latest version of the script is being loaded, I use the sys_mod_count value of the UI Script record in the the query string for the script element&#39;s src attribute. This way each time the UI Script is updated, the src URL changes and the browser downloads and caches the new version of the script.</p> <p>Below is the Jelly code for what I have just described.</p> <p><u>&lt;!-- script language=&quot;javascript&quot; src=&quot;license_page_angular_app.jsdbx?version=20&quot;&gt;

// load the script in this way so that when

// I change the script, the new version of the script is downloaded.

var loadScript = "";

var grScript = new GlideRecord("sys_ui_script");

grScript.addQuery("name", "license_page_angular_app");

grScript.query();

grScript.hasNext();

if(grScript.next())

{

//The mod count (grScript.sys_mod_count) will make the URL for the script unique

var src = "license_page_angular_app.jsdbx?v=" + grScript.sys_mod_count;

loadScript = src;

// Using the XML escape tags for the angle brackets that mark an HTML element

loadScript = '<script language="javascript" src="' + src + '"></script>';

}

loadScript;

/g:evaluate

g2:no_escape${jvar_licensePageAngularScript}/g2:no_escape

View original source

https://www.servicenow.com/community/developer-articles/create-a-script-element-on-a-ui-page-using-jelly-cache-busting/ta-p/2329860