AMD asynchronous module definition and Require. Js using jQuery and jQuery plug in methods

  • 2020-03-30 03:14:02
  • OfStack

AMD modules

The overall goal of the Asynchronous Module Definition (Asynchronous Module Definition) format is to provide a modular JavaScript solution available to today's developers.

The AMD module format itself is a proposal for defining modules in which both modules and dependencies can be loaded asynchronously. It has a number of unique advantages, including features that are inherently asynchronous and highly flexible, which can break the tight coupling between common code and module identities. It has been adopted by many projects, including jQuery (1.7).

RequireJS

RequireJS is a library of tools for module management on the client side. It can improve the performance and maintainability of the code by breaking it up into modules that can be loaded asynchronously or dynamically. Its module management complies with AMD specifications.

The advanced version of jQuery (1.11.1) removes define.amd.jquery


if ( typeof define === "function" && define.amd ) {
 define( "jquery", [], function() {
  return jQuery;
 });
}

JQuery is used in Require. Js

JQuery is very convenient to use in Require. Js, simple configuration is ok, for example:


//Simple configuration
require.config({

    //RequireJS loads all the code in a relative path, baseUrl. BaseUrl is typically set to the data-main property to specify the sibling directory of the script.
    baseUrl: "./js",

    //Third party script module alias,jquery than libs/jquery-1.11.1.min.js concise;
    paths: {

        "jquery": "libs/jquery-1.11.1.min.js"

    }

});

//Start using jQuery modules
require(["jquery"], function ($) {

    //Your code
    //Here you can directly use jquery methods such as $("#result").html("Hello World!") );

});

JQuery plug-ins are used in Require. Js

General jQuery plug-in format:

(function ($) {
    $.fn.m​​yPlugin = function () {
        //Your own plug-in code
    };
})(jQuery);

However, we can use Require. Js to load a jQuery plug-in.

;(function (factory) {
    if (typeof define === "function" && define.amd) {
        //AMD mode
        define([ "jquery" ], factory);
    } else {
        //The global model
        factory(jQuery);
    }
}(function ($) {
    $.fn.jqueryPlugin = function () {
        //The plug-in code
    };
}));

JQuery UI components are used in Require. Js

Similar to using jQuery UI components in Require. Js, you can just tweak the jQuery Widget Factory code and feel the jQuery UI dependencies load. Such as:


(function (widgetFactory) {

    if (typeof define === "function" && define.amd) {
        //AMD mode
        define("jquery.ui.widget", ["jquery"], function () {

            widgetFactory(window.jQuery);

        });
    } else {
        //The global model
        widgetFactory(window.jQuery);
    }
}
(function ($, undefined) {

    //JQuery Widget Factory code

}));


Related articles: