一、AMD(Modules/Asynchronous-Definition),Asynchronous Module Definition,异步模块定义,所有的模块将被异步加载,模块加载不影响后面语句运行。所有依赖某些模块的语句均放置在回调函数中。

基本语法

一、定义暴露模块: define(function() { return 模块 }), define([xxx], function() { return 模块 })

  1. //定义没有依赖的模块
  2. define(function(){
  3. return 模块
  4. })
  1. //定义有依赖的模块
  2. define(['module1', 'module2'], function(m1, m2){
  3. return 模块
  4. })

二、引入使用模块:require([xxx], function() {})

  1. require(['module1', 'module2'], function(m1, m2){
  2. 使用m1/m2
  3. })

核心实现

function require(url, callback) {
    // url可以换成List,然后遍历
    var $script = document.createElement('script')
  $script.src = url

  // 利用onload回调,实现依赖加载
  $script.onload = function (e) {
      // 省略callback检测
    callback()
  }
  document.body.appendChild($script)
}

优缺点

一、优点:

  • AMD模块定义的方法非常清晰,不会污染全局环境,能够清楚地显示依赖关系。AMD模式可以用于浏览器环境,并且允许非同步加载模块,也可以根据需要动态加载模块。