-
Notifications
You must be signed in to change notification settings - Fork 500
jQuery and AMD
As of jQuery 1.7, jQuery will register as an AMD module, but only if the AMD loader sets define.amd.jQuery to a true value.
This was done because jQuery is very popular, being used as part of third party script utilities like analytics scripts. In those cases, multiple versions of jQuery could be loaded on a page, outside of an AMD loader. However, since jQuery calls define, the AMD loader will be notified of each jQuery version loaded, if they are versions past jQuery 1.7.
This can cause problems for AMD code that is expecting a particular version of jQuery. The AMD loader should give the developer either special instructions or special loader tools to deal with this issue.
If the loader has done one of those two things, then it should set define.amd.jQuery to true.
For example, RequireJS has a jQuery: 'version string' config value it supports, and it only registers that version of jQuery as an AMD module. It also has a 'namespace' optimizer option that will place the define/require calls under a particular namespace, so that there is no global define call.
The almond API shim is only used for built resources, and it should be used with a function wrapper around the code, so its require and define are not visible to the outside page.
If a loader gives clear instructions to its users about the hazards of loading scripts outside of the AMD loader, and if it should only be used with all-AMD code on a page, it can also set define.amd.jQuery to true.
As an application developer, if your loader does not have this property set, you can manually set it in your application if you know you have full control over the page and are aware of the issue. In your top-level module/main.js, just set define.amd.jQuery = true;
before loading any modules.
In an ideal world, this special flag would not be needed. If jQuery was not as popular in third party libraries or had come out after broad AMD use, then there would be enough common understanding of the issues involved with third party code. However, due to jQuery's popularity in third party code, it was seen as best by the jQuery team to start slow with AMD registration and avoid errors that would be hard to track down and hard to fix, particularly if the AMD loader did not have any mitigations for it.
Over time, this special check may be removed from the jQuery code, but for the initial rollout for AMD support, it was seen as a safer approach.