The introduction of the Custom Code
codeless block opens up a lot of possibilities. One of them is importing external CSS files. This may become necessary when you need to embed an external UI component into your UI Builder application. For example, the AG Grid component comes with its own CSS files. Of course, you could copy/paste that CSS into a UI Builder theme extension, however, importing original CSS for a component seems like a better approach.
So here we go:
-
Switch to the
LOGIC
tab in UI Builder and click theFUNCTIONS
tab on the right side of the screen. Click the+ NEW FUNCTION
button:
-
Type in
loadCSS
in theCreate New Global Function
popup and clickCREATE
:
-
Click the gear icon in the function block, drag
input name [x]
into inputs and changex
tourl
. This will be the function argument:
-
Deselect the
with return
checkbox:
-
Click the
gear
icon to close argument definitions. Now we will add theCustom Code
block to the function’s logic. Locate theAdvanced
section in the Codeless blocks menu on the left and drag theCustom Code
block into the function:
-
Click
name
in theCustom Code
block and change it toloadCSSWithURL
. This is not an important step, but it is better to assign logical names yourCustom Code
blocks:
-
Click the gear icon in the
Custom Code
block. This will open the custom code editor. Click the field that saysAdd a new argument
and type incssURL
. Press enter to register the argument:
-
Paste the following code into the editor:
await new Promise(resolve => { const link = document.createElement('link') link.href = cssURL; link.rel = 'stylesheet' link.type = 'text/css' link.onload = () => resolve() document.head.appendChild(link); })
-
Click
SAVE and CLOSE
. -
Drag the
url
argument of the custom function to thecssURL
argument of theCustom Code
block:
At this point all the code and logic for loading an external CSS is ready. To use this functionality, you will need to use the new global function. For example, suppose you need to load the following css file:
https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css
Switch to the On Page Enter
handler:
Your new loadCSS
global function will be available in the Custom Functions
menu item. Drag the codeless block for the function into the On Page Enter
connector:
The last remaining step is to add the Text
connector to the url
argument of the loadCSS
function:
And finally enter the URL of the CSS to load:
You might be asking the question: “why did we use a global function that wraps the custom code?” The reason is convenience. Global functions can be reused between different pages of your app. By defining a global function (loadCSS
) it now can be reused and you will be saving time since all the steps described above would need to be done once.