Question:
Are global variables in server-side JavaScript libraries shared across the board regardless of the user/session ?
Answer:
Yes, global variables defined in server-side JavaScript libraries are
initially indeed globally shared across sessions.
However, they are
not guaranteed to be available for the life-cycle of the application and might get discarded by the run-time at any time.
Therefore, it is
not recommended to rely on this.
To understand the reasons for this, let's look at how server-side script libraries work:
A script library is loaded once a page requests it. It is compiled, the statements outside a function body are executed, and a list of global variables is maintained.
For example, each function defined in the library is a global variable of type "function", as well as the constants you defined.
How long this data is kept in memory is undefined. If the operating system is reclaiming memory, then this data is discarded, and will be reconstructed when a page requests it again. After it has been discarded and reconstructed, the original value of the global variables are lost.
Note that data cannot be discarded while they are actively in use by a page, so it is safe during the request phase for a page.
The recommended way to reliably store and share global variables across user sessions is to use the applicationScope.
To illustrate this, consider the following sample XPage:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.resources>
<xp:script src="/global.jss" clientSide="false"></xp:script>
</xp:this.resources>
<xp:this.afterPageLoad>
<![CDATA[#{javascript:addToCounter(5); print("Updated counter value: "
+ applicationScope.counter);}]]>
</xp:this.afterPageLoad>
</xp:view>
and this code in the associated server-side "global.jss" JavaScript library:
applicationScope.counter = 0;
print("Initial counter value: " + applicationScope.counter);
function addToCounter(value) {
applicationScope.put("counter", applicationScope.counter + value);
}
When the page gets loaded the very first time, the server console output will be:
HTTP JVM: Initial counter value: 0
HTTP JVM: Updated counter value: 5
Any additional page loads from different clients will continue to increase the global counter value by 5 each time the page gets loaded:
HTTP JVM: Updated counter value: 10
HTTP JVM: Updated counter value: 15
HTTP JVM: Updated counter value: 20
HTTP JVM: Updated counter value: 25