Skip to content

How to load an extra Javascript file from a widget.

Thomas Bonnesen edited this page Feb 13, 2024 · 1 revision

How to load an extra Javascript file from a widget.

All files that you add to the widget zip file can be accessed from the web portal.

If you want to load and JS file, then a Js script tag needs to be added to the DOM. This can be done with vanilla javascript or a mootools function:

#!javascript
Asset.javascript(this.getWidgetRootPath() + "myscript.js", {
    id: "script ID",
    onload: function(){
       
    },
    onFailure: function (msg) {
        Logger.error("Error loading script", msg);
    }
  });

In this example, the "this" is the widget. The widget has a function called getWidgetRootPath that will return the path to "the root of the zip file."

It is a good idea to add an event on onDestroy of the widget and remove the script when the widget is destroyed.

#!javascript
this.addEvent('onDestroy', () => {
    var elem = $('script ID');
    if ($defined(elem)) {
      elem.remove();
    }
  });