Attention points when writing jQuery plug in
- 2021-07-22 08:48:27
- OfStack
Write the jQuery plug-in, and there are 1 points to pay attention to (keep adding).
Support UMD
Now front-end development pays attention to modularity, so jQuery plug-in is also best able to take into account modularity.
There are several modular modes: AMD, CommonJs and UMD.
AMD (Asynchronous Module Definition)
Asynchronous module definition, can load or depend on other modules asynchronously, supported libraries such as Require. js, Sea. js.
Examples:
// xxx-plugin.js
define(['jquery'], function ($) {
function myFunc(){};
return myFunc;
});
CommonJs
Javascript can be defined as an Node module.
Examples:
var $ = require('jquery');
function myFunc(){};
module.exports = myFunc;
UMD (Universal Module Definition)
In order to be compatible with AMD and CommonJs styles, UMD appeared.
Code:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node, CommonJS-like
module.exports = factory(require('jquery'));
} else {
// Browser globals (root is window)
root.returnExports = factory(root.jQuery);
}
}(this, function ($) {
function myFunc(){};
return myFunc;
}));