RequireJS manual

Introduction

RequireJS is a loader for JS files and modules. It is an optimization for running in a browser, and can also be used in other JS environments, such as Rhino and Node.


compatibility

IE6 , Firefox 2 , Safari 3.2 , Chrome 3 , Opera 10


Why use RequireJS

Without using the module loader, all js files are written in HTML files. As the project becomes more complex, JS files will become modularized. Each module corresponds to a JS file and needs to be loaded in turn. The stronger the dependency, the later the load is. When the dependencies are complex, the issue of code loading order becomes complicated. RequireJS was born. Its purpose:

(1) It is the asynchronous loading of the JS file first to prevent the page from losing response.

(2) Manage the dependencies between modules to facilitate code writing and maintenance.


use

Default: The file extension is.
(1) Download the js file.

(2) Load the file in the HTML document. (The data-main attribute tells requireJS to load main.js after requireJS is loaded. Asynchronous loading. Main.js is the entry file of JS, ensuring the single entry principle )

      <head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>RequireJS的引用</title>
		/*官方推荐所有JS文件使用RequireJS加载器进行加载,以达到最大优化*/
		<script data-main="script/main" src="script/require.js"></script>
	</head>
	<body>
		<button οnclick="javascript:say_hello();">Hello RunJS!</button>
		/*若有JS代码不需要加载器加载,则将其写在body后面,保证HTML,css的正常加载*/
		<script src="script/index.js"></script>
	</body>

(3) Configuration main.js . Used to load other JS modules or files you need to load.

requirejs.config({
    //如是基本路径一致,可以配置基础路径baseUrl
    baseUrl: 'js/lib',
    //提前配置好每个模块的路径,方便下面的加载使用。下面app.js就是js/app.js文件。默认文件后缀是JS
    paths: {
        app: '../app'
    },
 shim: {//这里可以配置不符合AMD规范的JS文件    angular:{export:['angular']}}
});

 //requirejs接收两个参数。第一个参数接收一个数组,插入模块。第二个参数,是一个函数,调用模块
//app代码入口
requirejs(['jquery', 'canvas', 'app/sub'],function ($, canvas,sub) { //jQuery, canvas and the app/sub 模块已经加载可以正常使用});


(4)定义一个模块,如app.js 更多模块定义

//define函数接受两个参数,依赖模块以及自身模块函数
	define(['jquery'],function($){ 
	//自身模块代码
	})


(5)RequireJS插件的使用。如domReady同上。



Guess you like

Origin blog.csdn.net/u010682774/article/details/74178215