Suresh kumar
Suresh kumar

Reputation: 505

What is 'typeof define === 'function' && define['amd']' used for?

What purpose does the following code serve? What does factory function do here? Here root is window object. Is factory a default java script function? In what kind of scenarios this type of code can be used. This code is from toggle.js from Simon Tabor. Zepto and ender are libraries. Is this mostly used in libraries.

   if (typeof define === 'function' && define['amd']) {
        define(['jquery'], factory);
     } else {
      factory(root['jQuery'] || root['Zepto'] || root['ender'] || root['$']|| $);
    }

Upvotes: 31

Views: 20081

Answers (2)

simohe
simohe

Reputation: 651

This is part of a Universal Module Definition (short UMD). It detects the environment and then handles dependencies and exports.

Depending on what environments the module supports (require.js, nodejs, browser, ...), the UMD might look different. See https://github.com/umdjs/umd for some templates of this loader.

What is special here is the loading of the one dependency when running in the browser. It loads jQuery OR Zepto OR ender OR $, whatever it finds first. So it allows the user to load any of this with the <script> tag (and not a specific one).

Upvotes: 1

Aran Mulholland
Aran Mulholland

Reputation: 23945

This code checks for the presence of require.js, a JavaScript dependency management library.

If 'define' is not undefined and it is a function and 'amd' (asynchronous module definition) is also defined then the code assumes that require.js is in play.

If this is so then it defines 'factory' and passes jQuery to it as a dependency. Otherwise it sets up the dependencies that the code needs by attaching them to the root object.

As for what 'factory' is: it is not defined by the Javascript framework, it will be a function in the same file most likely. It will take the parameter jQuery.

Upvotes: 36

Related Questions