Can I write a javascript file that optionally uses require.js to specifies dependencies when it is available?

☆樱花仙子☆ 提交于 2019-12-02 13:59:50

问题


I need to write a javascript plugin that can be used both as an AMD module and as a non-AMD (synchronously loaded) javascript file.

It has a dependency on the "Jockey.js" and jquery libraries.

In other words, I'd like to structure the file so that it doesn't fail when its used in a traditional non-async html structure (loaded via a script tag, after its dependencies are loaded via script tags), but so that it will also be able to work as an AMD module without shim, and specify its dependencies. Can this be done, or is shim the only way to do this?


回答1:


It can be done. I've got one such plugin right here. Here's the general structure:

(function (factory) {
    // If in an AMD environment, define() our module, else use the
    // jQuery global.
    'use strict';
    if (typeof define === 'function' && define.amd)
        define(['jquery'], factory);
    else
        factory(jQuery);
}(function ($) {
    'use strict';

    // This is the plugin proper.
    $.fn.myMethod = function(/* ... */) {
        // Code for the method...
    };
}));

A plugin that needs other things than just jQuery would use the structure above with the following modifications:

  1. A call to define that lists the additional modules needed.

  2. A factory(jQuery) call (in the non AMD branch, used when RequireJS is not loading the plugin) that passes additional values from the global space after jQuery.

  3. A factory function function ($) that has additional arguments to receive the additional values passed to it.

So if the plugin needs module foo which exports itself in the global space as foo and with a RequireJS configuration that names it "foo", then:

(function (factory) {
    // If in an AMD environment, define() our module, else use the
    // jQuery global.
    'use strict';
    if (typeof define === 'function' && define.amd)
        define(['jquery', 'foo'], factory);
    else
        factory(jQuery, foo);
}(function ($, foo) {
    'use strict';

    // This is the plugin proper.
    $.fn.myMethod = function(/* ... */) {
        // Code for the method...
        foo.blah();
    };
}));


来源:https://stackoverflow.com/questions/21351621/can-i-write-a-javascript-file-that-optionally-uses-require-js-to-specifies-depen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!