The Zurich release has arrived! Interested in new features and functionalities? Click here for more

How to include a JavaScript library within the ServiceNow head tag?

wolfgangb
Giga Contributor

I understand that ui scripts that are marked as global are loaded with every page that ServiceNow loads. These pages are running within an iframe.

How can I include a JavaScript library within the global head HTML tag for each page?

1 ACCEPTED SOLUTION

ChrisBurks
Giga Sage

If you place something like below in a UI script and make that global should work.



(function(){


  var top = getTopWindow().window.document.querySelector('head');   // reach out to the parent window and get the head element


  var script = document.createElement('script');   //create a new script element


  script.src = 'path/to/js/library';   //sets the src attribute


  script.type = 'text/javascript';   //sets the type attribute


  top.appendChild(script);     // appends the newly created script element at the end of the top window head element


})();


topWindow.png


View solution in original post

7 REPLIES 7

ChrisBurks
Giga Sage

If you place something like below in a UI script and make that global should work.



(function(){


  var top = getTopWindow().window.document.querySelector('head');   // reach out to the parent window and get the head element


  var script = document.createElement('script');   //create a new script element


  script.src = 'path/to/js/library';   //sets the src attribute


  script.type = 'text/javascript';   //sets the type attribute


  top.appendChild(script);     // appends the newly created script element at the end of the top window head element


})();


topWindow.png


Hi ChrisB,

I tried to use the function but I get 'Uncaught ReferenceError: getTopWindow is not defined' error. Am I doing something wrong? I am on Kingston patch 4.

 

var top = getTopWindow().window.document.querySelector('head');   // reach out to the parent window and get the head element

I tested on Kingston patch 6 and it works. I don't have a patch 4 environment to test on.

Aside from that where exactly are you trying to use the this function?