[requirejs] basic summary

Keywords: JQuery Attribute github Spring

1. Recognition Recognition Recognition Recognition Recognition Recognition Recognition Recognition Recognition

                                                                                                 GitHub's own code

RequireJs is a js file for modular management of js files, which belongs to an implementation of AMD specification; it can improve speed and code quality; see the official website for details: http://requirejs.org/


2. Use * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *


2.1 entry

When configuring the JS file of require.js, add the data-main attribute, which is the entry of js.

Note: The js file specified by data-main is loaded asynchronously, so when multiple js are specified on the page, the loading order cannot be guaranteed even if placed below the data-main.

For the selection of entry files:

If the project divides a page into several layouts (general: the whole page, other layouts fill the page; header: the head of the page, fill genneral; footer: the tail of the page, fill genneral; main: the body of the page, different pages are created, fill general, etc.), you can introduce matching in genneral page. Configure file; introduce js of each page in main page; so that the configuration file can be loaded before js of each page, and the configuration file can be used in js of main page.

(2) If this layout is not used, then the entry files of different jsp pages use the js files of each page. If you want to define new modules using configuration files, you can add the js of configuration files to the module array referenced by definition, and then add the js name that has been configured in the configuration file. When you need to use it, you can use require to load the configuration. The js name in the file, otherwise, cannot be referenced; the example is as follows:

Define the common util.js module, and the configuration file uses the main.js below

/**
 * Created by xlch on 2016/12/27.
 */
//jquery configured in the configuration file is used here, so the configuration file js, jquery are referenced in turn
//Although the main module is referenced here, it only declares jquery, which still requires regular requires or definitions to invoke.
//The jquery referenced here does not exist in the js/lib/jquery path, but is configured in man.js, so the following requirements are required
define(['require','module','../main', 'jquery'],function (require,module) {
    //This is where jquery is really loaded; and jquery must be defined in the module array of define
    var $ = require("jquery");

    var utils = {};
    utils.quick = {
        click:function (method,node) {
            var list = null;
            if (node) {
                list = $(node).find("[data-click]");
            }else {
                list = $("[data-click]");
            }
            list.on("click",function (eventObject) {
                var click = $(this).data("click");
                if (click && method[click]) {
                    return method[click].apply(this,[eventObject]);
                }
            });
        },
        offClick:function (method, node) {
            if (node) {
                $(node).find('[data-click]').off('click');
            }else {
                $('[data-click]').off('click');
            }
        }
    };
    return utils;
});


Entry document Chestnut:

<script src="${ctx}/js/require.js" data-main="${ctx}/js/app/home"></script>


2.2 requirejs configuration file


Common configuration properties

baseUrl: The root path for all modules to find,

If the baseUrl parameter is not set and the data-main attribute is not used, the default value of baseUrl is the location of the HTML page loading require.js;

If the baseUrl parameter is not set and the data-main attribute is used, then the baseUrl is the path of the data-main;

paths: If the module name cannot be found directly under baseUrl, the option is used to map the path, such as a directory containing multiple levels or a directory above baseUrl; No. js suffix is required;

bundles:

shim: A traditional script for configuring incompatible modules, i.e. without defining () to declare dependencies and without setting a module name; for example, backbone.js;


Note: The shim configuration only sets the dependencies of the code. To actually load the modules specified or involved by shim, you still need a regular require/define call. Setting up shim itself does not trigger code loading.

There are two main parameters below:

deps: Used to declare dependencies, in the form of arrays

exports: Define the name of a module as a global reference to the js

Modules that exist only as plug-ins for jQuery or Backbone without exporting any module variables can be simply configured as dependent arrays.

requirejs.config({
    shim: {
        'jquery.colorize': ['jquery'],
        'jquery.scroll': ['jquery'],
        'backbone.layoutmanager': ['backbone']
    }
});

waitSeconds: The longest waiting time for js to load, and the default time for js to load is 7 seconds.



Configuration file Chestnut:

main.js:

/**
 * Created by xlch on 2016/12/27.
 */
require.config({

    //Root paths for all modules to find
    baseUrl: 'js/lib',

    //The aim is to simplify the tedious reference names by requiring ('jquery'), function (){}).
    //Paths are relative to baseUrl
    paths: {
        "jquery":'jquery/jquery-3.1.1.min',
    },

    // Configure js that are not amd specifications, increase dependencies and output names
    shim: {          //
        'backbone':{
            depts:['jquery','underscore'],
            exports:'Backbone'
        },
        'underscore':{
            exports:'_'
        },
    },

    //The longest waiting time for loading js, the default time is 7 seconds
    waitSeconds: 30,

    //The end of the JS loaded after main.js is suffixed to prevent caching, but the production environment needs to be removed
    // urlArgs: "bust=" +  (new Date()).getTime(),

    // Application level parameters, used by module.config(), unsolved
    config:{
        'name':{
            na:'xlch'
        },
    },
});





 2.3 define

Define is used to define a module, which can be called by require; note here that the result must be returned, whether object or function; because the module defined by definition is called by require; so that definition can be captured by other external modules, that is to say, the module can be used;

For example, the above definition of a common util module, see the example code util.js above;

copy again, using the main.js above:

/**
 * Created by xlch on 2016/12/27.
 */
//jquery configured in the configuration file is used here, so the configuration file js, jquery are referenced in turn
//Although the main module is referenced here, it only declares jquery, which still requires regular requires or definitions to invoke.
//The jquery referenced here does not exist in the js/lib/jquery path, but is configured in man.js, so the following requirements are required
define(['require','module','../main', 'jquery'],function (require,module) {
    //This is where jquery is really loaded; and jquery must be defined in the module array of define
    var $ = require("jquery");

    var utils = {};
    utils.quick = {
        click:function (method,node) {
            var list = null;
            if (node) {
                list = $(node).find("[data-click]");
            }else {
                list = $("[data-click]");
            }
            list.on("click",function (eventObject) {
                var click = $(this).data("click");
                if (click && method[click]) {
                    return method[click].apply(this,[eventObject]);
                }
            });
        },
        offClick:function (method, node) {
            if (node) {
                $(node).find('[data-click]').off('click');
            }else {
                $('[data-click]').off('click');
            }
        }
    };
    return utils;
});



NOTE: To be able to use a known module, both define and require must be placed in an array of module names ([]). Both first-level and multi-level require are in an array.


2.4 require

require is used to call the define d module to complete page rendering; it differs from definition in that it has no return value and cannot be perceived by other external modules.

Sample code: you can use require to load when you use a js;

/**
 * Created by xlch on 2017/2/6.
 */
//Load the configuration file js and the module provided by default
require(['../main','module'],function (main,module) {

    require(["../help/util"],function (util) {
        util.quick.click({
            delete:function () {
                alert("delete");
            }
        });
        
        require(['underscore'],function (_) {
            var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
            console.log(_.pluck(stooges, 'name'));
        });
    })
})


If you want to use the module configured in the configuration file while loading the configuration file, such as jquery configured in main.js above:

This can be done:

require(['require', '../main', '../help/util'], function (require,main,util) {

    util.quick.click({
        delete: function () {
            alert("delete 222");
        }
    });

    require(['backbone'], function (Backbone) {
        Backbone.Model.extend({});
    });

    require(['jquery'],function ($) {
        console.log($("#h2").text());
    })
})

But if I use jquery as define d, I will report an error. jquery 404 is not found

The address he is looking for is js/app/jquery, but the baseUrl configured in my main is js/lib, and the path used here is js/app;

According to the inference, the main.js has not been loaded at this time. I don't know whether the inference is correct or not.

//Errors will be reported and js/app/jquery.js cannot be found, while the real path of jQuery is configured in main.js
//Note: Should main.js not be loaded here? Generate rules according to baseUrl above
//If data-main is set and baseUrl is not set, then baseUrl is the path of data-main.
//That is, js/app/home.js pasted at the entrance is completely consistent;
require(['require', '../main', '../help/util', 'jquery'], function (require,main,util) {
    var $ = require("jquery");
    console.log($("#h2").text());

    util.quick.click({
        delete: function () {
            alert("delete 222");
        }
    });

    require(['backbone'], function (Backbone) {
        Backbone.Model.extend({});
    });

    require(['jquery'],function ($) {
        console.log($("#h2").text());
    })
})

If I remove jquery from require's module array here, I can run successfully; the following code adjustments

require(['require', '../main', '../help/util'], function (require,main,util) {
    var $ = require("jquery");
    console.log($("#h2").text());

    util.quick.click({
        delete: function () {
            alert("delete 222");
        }
    });

    require(['backbone'], function (Backbone) {
        Backbone.Model.extend({});
    });

    require(['jquery'],function ($) {
        console.log($("#h2").text());
    })
})

In addition, the module array of require provides domReady!, which ensures that the function of the module can be invoked only after the DOM is ready.
require(['domReady!'], function (doc) {
   
        //After waiting for the DOM to load, call the function

});


In order to prevent the requirejs from overtime due to long loading time, the maximum waiting time for the waitSeconds configuration can be added to the main.js configuration file, or the domReady () method call can be used.

require(['domReady'], function (dom) {
  domReady(function () {
   // Execution of DOM after loading
  });
});


"A brief summary, to be continued"

Posted by hossfly007 on Sun, 24 Mar 2019 13:09:29 -0700