Search code examples
javascriptrequirejsamdjs-amd

have requirejs to run callback when the module is loaded


I need to load css when my module is loaded, so I did it like this using shims :

function loadCss(url) {
    var link = document.createElement("link");
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = url;
    document.getElementsByTagName("head")[0].appendChild(link);
}

requirejs.config({ paths: paths, shim: {
    'easyzoom': {
        'deps': ['jquery'],
        init: function () { loadCss('/lib/easyzoom/css/easyzoom.css'); }
    }}
});

It works for other libraries like Datatables because they are non-Amd modules. But for Amd modules, requireJs doesn't look for shims so will not raise my init function.

Is there any way to have a callback called after a module is loaded ? Or load an Amd module as it was a plain javascript file to have shims looked for ?


Solution

  • Defining a shim for a proper AMD module (one that calls define) results in undefined behavior.

    What you can do is use map as follows:

    map: {
        '*': {
            easyzoom: 'easyzoom-intercept'
        },
        'easyzoom-intercept': {
            easyzoom: 'easyzoom'
        }
    }
    

    What this does is specify that when any module ('*') requires the module easyzoom, the module easyzoom-intercept should be loaded instead. However, when easysoom-intercept wants to load easyzoom, the module easyzoom should be loaded. You then create a easyzoom-intercept module like this:

    define([easyzoom], function (ez) {
        loadCss('/lib/easyzoom/css/easyzoom.css');
        return ez;
    });
    

    This code will be executed as soon as easyzoom is loaded.