简体   繁体   中英

Javascript app as an AMD module with external dependencies

I am writing a Javascript application that is supposed to be hosted on various sites. The application itself uses jQuery and jQuery UI. I am aware of jQuery.noConflict(true) trick and using it currently so not to pollute the global space. My aim is to always keep jQuery and any of its plugins local to my application so as not to conflict with anything on the hosting site. It should be possible for the hosting site to load its own jQuery (maybe different version) and add some plugins.

Now, I would like to structure the app as an AMD module. It is OK with me to require from the hosting site to use an AMD loader (require.js, curl, etc.) but I wouldn't like to require any particular one - just anything conforming to AMD API (yep, I know it's not 100% ready yet).

Is it at all possible? Can I do it in an interoperable way, so that the hosting site can use eg either requirejs, curl or Dojo AMD loader?

For example, with this:

define(['jquery'], function($) {
    var myLocaljQuery = $.noConflict(true);

    ... my app module implementation here ...

});

how can I specify the path for jQuery that my application wants to use? As far as I understand, I cannot do anything like this:

require.config({
    paths: {
       'jquery' : 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min'
    }
});

define(['require'], function(require) {
    require(['jquery'], function($) {
        var myLocaljQuery = $.noConflict(true);

        ... my app module implementation here ...
    });
});

because the first require is a global object and this is specific to requirejs.

After doing some more research, I think it is not feasible at the moment. At least for one thing - the module ids are global within AMD context, so I cannot simply use "jquery" or "jquery-ui" module IDs in my application and be sure that there won't be any conflict when someone hosts my application and wants to use jQuery (potentially other version) through AMD too. See for example here :

curl.js does not prevent conflicts with third-party scripts that may load other versions of jQuery as an AMD module.

As far as I understand, AMD is aimed at modularizing stuff within your own app. It doesn't have much support for integration with third-party apps, at least not when you want to do some encapsulation to avoid conflicts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM