The use of requirejs

AMD Specifications

  1. AMD is the abbreviation of "Asynchronous Module Definition", which means "Asynchronous Module Definition". It loads the module asynchronously, and the loading of the module does not affect the execution of the statement following it. All statements that depend on this module are defined in a callback function, which will not run until the loading is complete.
  2. AMD also uses the require() statement to load modules, but unlike CommonJS, it requires two arguments:
require([module], callback);
The first parameter [module] is an array whose members are the modules to be loaded; the second parameter callback is the callback function after the loading is successful. E.g:
require(["fun"], function(fun) {
		console.log("content finish...")
		fun.fun();
	});

Why use requirejs

  1. First of all, when loading, the browser will stop the rendering of the page. The more files are loaded, the longer the page will become unresponsive.
  2. Since there are dependencies between js files, the loading order must be strictly guaranteed (for example, 1.js in the above example should be in front of 2.js), and the most dependent modules must be loaded last. When the dependencies are very complex At times, it becomes difficult to write and maintain code.
So requirejs is to solve these two problems, realize the asynchronous loading of js, and manage the dependencies between modules

Usage of require:

1. Introduce requirejs

<script src="js/lib/require.js"></script>

2. Set the entry file

<script data-main="js/main" src="js/lib/require.js"></script>
data-main is used to set the entry of requirejs, this file will be loaded first by requirejs, you can omit the .js suffix

3. Configuration

Configure requirejs in js/main
require.config({
	baseUrl: 'js',
	paths : {
		'useful': 'useful / useful',
		'server' : "util/server"
	},
	shim : {
		
	}
});
baseUrl is used to set the root path of requirejs. For example, the full path of util is js/util/util.js
Several configuration cases:
  • Configuration files for remote servers
paths: {
		"jquery" : ["http://libs.baidu.com/jquery/2.0.3/jquery", "js/jquery"],
		sendReq: "../lib/sendReq",
		vue: ['https://cdn.bootcss.com/vue/2.2.2/vue']

	}
jquery configuration, if the remote server cannot access, then access the local js/jquery
  • Non-AMD modules can be configured like this
require.config({
	paths : {
		underscore : "js/underscore"
	},
    shim: {
        "underscore" : {
			deps: ['underscore', 'jquery'],
            exports : "_";
        }
    }
})
require(["underscore"], function(_){
    _.each([1,2,3], alert);
})
deps: the dependency of the table name module, the name when the exports table name is called externally


4. Define the module

define(function(){
	var fun = function(){
		console.log("call fun...");
	}
	
	return {
		fun : fun
	}
})

5. Use

require(["util"], function(fun) {
		console.log("load finish...")
		fun.fun();
	});
The fun in the callback function is the object exported by the util module


Notice

  1. It should be noted that there are several cases of the default path of requirejs
    1. If you do not configure the entry file, then if you call require(['util']), the default directory of requirejs is its own directory, which means that requirejs will read util.js from its own directory.
    2. If baseUrl is not configured, the default directory is the directory where the entry file is located
    3. Configured baseUrl, the default directory is baseUrl
  2. If a module ID conforms to one of the following rules, its ID parsing will bypass the regular "baseUrl + paths" configuration and instead load it directly as a script relative to the current HTML document:
    1. ends with ".js";
    2. To ... beginning;
    3. Contains URL protocols, such as "http:", "https:"
  3. Question about data-main loading
The scripts you set up in data-main are loaded asynchronously. So if you configure other JS loading in the page, there is no guarantee that the JS they depend on has been loaded successfully.

require single page usage

console.log("config...")
require.config({
	// baseUrl: 'js',
	paths : {
		'useful': 'useful / useful',
		'server' : "util/server"
	},
	shim : {
		
	}
});

require (['util'], function (util) {
	util.fun();
});

Multi-page usage of require

When using multiple pages, you can use the configuration of config, but you need to introduce the js corresponding to the page in the page, for example:

<script data-main="js/require-config" src="https://cdn.bootcss.com/require.js/2.3.5/require.js"></script>
		<script src="js/module/index.js" type="text/javascript" charset="utf-8"></script>
But because data-main is loaded asynchronously, if you use require in index.js, the require-config may not be loaded, so the loading fails, so you need to remove data-main and write it in index.js like this, for example :

require(['js/require-config'], function() {
	require(["util"], function(fun) {
		console.log("load finish...")
		fun.fun();
	});
});
Specific api reference: click to open the link

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325983144&siteId=291194637