Using an external JavaScript (not Dojo module) in your ICN plugin

Sometimes you need to use an external JavaScript libraries in your plugin, because you don’t want to reinvent the wheel. Problem is that often those libraries are not Dojo modules. So how to use them in your dojo class?

Well that’s simple, dojo provides an generic script injection mechanism. Everything declared in the external script will be available in your class. Code is the following:

require(["http://host.com/stuff.js"], function(){
    // Everything declared in stuff.js is available here
});

You can link to an http location, or relative location into your project, for instance /application/stuff.js.

Now how to use that in your plugin? You can place your JavaScript file in another application or a CDN to refer it with an http protocole, example:

require(["http://host.com/application/stuff.js"], function(){
    // Everything declared in stuff.js is available here
});

Or you can leave the file in your plugin so everything is embedded when you deploy:

require(["plugin/MyPluginID/getResource/jszip/zip.js"], function () {
  // Here I can use the variable zip
});


The only downside of this method is that if ICN changes the way they are referencing resources within the plugin, that would be broken. With the first method you are safe, but another solution would be getting dynamically the resource URL, which looks like this:

var myPluginResource = Request.getPluginResourceUrl("MyPluginID", "jszip/zip.js")
require([myPluginResource], function () {
  // Here I can use the variable zip
});

That way you should be safe for future update of ICN, except if they change the getPluginResourceUrl, which is unlikely since it is a public API.

You can declare your script in your code to load it only if you need it, like I did here, or for simplicity sake (or because you will always use it), you can add it to the requires of your class, and just not map it to any variable in the callback function:

define([ "dojo/_base/declare", "dojo/_base/lang", "dojo/aspect", "ecm/model/Action", "plugin/MyPluginID/getResource/jszip/zip.js"], function (
     declare, lang, aspect, Action
) {
    return declare(Action, {
        // Here zip is available
    });
});

Basic but good to know.

 

 

Leave a Reply