zoukankan      html  css  js  c++  java
  • JavaScript 模块化加载

    存在AMD(Asynchronous Module Definition异步模块定义)规范和CMD(Common Module Definition通用模块定义)规范。
    对于依赖的模块,AMD是提前执行,CMD是延迟执行;并非绝对,CMD推从as lazy as possible;
    AMD推从依赖前置,CMD推从依赖就近;
    AMD的API默认一个当多个用,CMD的API职责单一。

    一个简单的开始,使用Sea.js模块化框架,该框架遵循CMD规范,简单的使用如下:

    1 define(function(require, exports, module) {
    2     exports.name="xf_z1988";
    3     exports.getnm=function(){
    4         return exports.name;
    5     };
    6 });
    定义一个CMD模块define_test_exports
    1 define(function(require, exports, module) {
    2     module.exports={
    3         name:"xf_z1988 module.exports test"
    4     };
    5 });
    定义个CMD模块define_test_module_exports
     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
     5 <style rel="stylesheet" type="text/css">
     6 </style>
     7 <script src="http://seajs.github.io/examples/sea-modules/seajs/seajs/2.1.1/sea.js"></script>
     8 <script type="text/javascript">
     9 if(typeof define === "function" && define.cmd){
    10     show();
    11 }
    12 function show(){
    13     seajs.config({
    14         // 定义基本路径.
    15         base:"/",
    16         // 别名.
    17         alias:{
    18             "jquery":"http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js",
    19             "define_test_exports":"http://files.cnblogs.com/xf_z1988/js_cmd_define_test_exports.js",
    20             "define_test_module_exports":"http://files.cnblogs.com/xf_z1988/js_cmd_define_test_module_exports.js"
    21         },
    22         // 提前加载.
    23         preload:["jquery"]
    24     });
    25     // 在页面中加载模块.
    26     seajs.use(["jquery","define_test_exports"],function(_$,x){
    27         $(document).ready(function(){
    28             document.body.innerHTML+=x.name+"_1<br/>";
    29         });
    30     });
    31     // 定义模块
    32     define(function(require,request,module){
    33         // 同步加载一个模块.
    34         var xd=define("define_test_exports");
    35         // 异步加载一个模块,在加载完成时,执行回调
    36         require.async("define_test_module_exports", function(x) {
    37             $(document).ready(function(){
    38                 document.body.innerHTML+=x.name+"_2<br/>";
    39             });
    40         });
    41     });
    42 }
    43 </script>
    44 </head>
    45 <body></body>
    46 </html>
    一个使用Sea.js来模块化的例子

    未完成

  • 相关阅读:
    Git查询
    HDU-3038 How Many Answers Are Wrong 并查集
    CodeForcesEducationalRound40-D Fight Against Traffic 最短路
    HDU-6109 数据分割 并查集(维护根节点)
    ZOJ-3261 Connections in Galaxy War 并查集 离线操作
    AtCoderBeginner091-C 2D Plane 2N Points 模拟问题
    HDU-1878 欧拉回路 欧拉回路
    [笔记-图论]Floyd
    [笔记-图论]Bellman-Ford
    [笔记-图论]Dijkstra
  • 原文地址:https://www.cnblogs.com/xf_z1988/p/javascript_amd_cmd.html
Copyright © 2011-2022 走看看