How to implement dependancy injection for catalog client scripts and UI policy scripts

kevinanderson
Giga Guru

We have some catalog items where the UI scripts and UI policy scripts get rather complex, and often are repeated (copy-paste) when different variable scripts need to share functionality. Currently if we want to share a client side JS library with the catalog client script code block,   we have to add the library to a macro, and add the macro to the variable list.

The macro approach for client script dependencies   seems problematic for onload scripts, and I have found occurrences where catalog client scripts for onload   events   may begin executing before the script call in the macro finishes fetching the library...so our onload code fails if it is not wrapped in a setTimout with a 1/2 second delay.     I really don't want to implement the full script in the macro.   It seems like that is just shifting the problem.   Client scripts should live in the client scripts tables...

How do other developers handle client side script dependencies in catalog client scripts and catalog UI policy scripts?     How do you prevent that problem of the same code getting copy-pasted over and over when variable scripts need to share functionality?

I don't like setting a huge litany of scripts to load globally...and I would really like a convent way to inject client side script libraries into the catalog item form for use by these catalog client scripts that are attached to variables on the form.

7 REPLIES 7

sumeet_n
Kilo Guru

Hi Kevin, really looking forward for the responses to this question.



From what i understand from your requirement - i thought that is what Global UI scripts are used for. I mean if I want to include any external JS library, I would just create global UI Script which will be loaded all the time in browsers and we could use whatever functions defined within them from any client script. No need of hidden UI Macro. You may find below links related.




Adding AngularJS to your ServiceNow instance-John Andersen


UI Scripts - ServiceNow Wiki


You are correct, I can use a global script for this.   Problem solved.


But   I don't want to be polluting every single page in the platform with files that are only used by a few pages in the service catalog.



The idea is to find a way to elegantly inject a common library of functions into only the pages that need that custom functionality, specifically catalog client scripts in this case.


BillMartin
Mega Sage

Hi @kevinanderson ,

 

I have created this article on how to apply dependency injection in ServiceNow.

 

A Guide for Architects and Developers Using Dependency Injection and Object-Oriented Design