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

你离开我真会死。 提交于 2019-12-02 03:16:14

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