Plugin API Reference Documentation: Appendix IV: Loading external libraries

linkPlugin API Reference Documentation: Appendix IV: Loading external libraries

The plugin execution context is isolated so it can loosen restrictions the application imposes on loading external resources. There are a couple patterns that can be used in plugin code to load external dependencies, depending on how the dependency is packaged.


linkLoading browser builds

The simplest dependency to load is a library that has a browser build. This is a build that can normally be used in a <script> tag - in plugin code a script tag can be appended to the document to load the dependency.


For example, to load the RecordRTC library's browser build:

_loadRecordRTC() {
if (this._haveLoadedRecordRTC) return Promise.resolve(true);
 
return new Promise(function(resolve) {
const script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", "https://www.WebRTC-Experiment.com/RecordRTC.js");
script.addEventListener("load", function() {
this._haveLoadedRecordRTC = true;
resolve(true);
});
document.body.appendChild(script);
});
}

A couple things to note in the above code:

The plugin execution context is kept loaded, so the dependency doesn't need to be loaded on every single call to the plugin - only the first call.

The library in question - RecordRTC - will be available as window.RecordRTC because it is packaged up as a browser build.

This can be used in the plugin's actions as:

async insertText(app) {
await this._loadRecordRTC();
 
// ... remaining plugin code can reference `window.RecordRTC`
}


linkLoading UMD builds

Dependencies that define UMD modules can be loaded with a small code shim:

async _loadUMD(url, module = { exports: {} }) {
const response = await fetch(url);
const script = await response.text();
const func = Function("module", "exports", script);
func.call(module, module, module.exports);
return module.exports;
}


Given a dependency that provides a UMD build, the above helper can be used as:

async imageOption(app, image) {
const metaPNG = await this._loadUMD("https://www.unpkg.com/meta-png@1.0.6/dist/meta-png.umd.js");
 
// ... remaining plugin code can use `metaPNG.*`
}