RequireJS Step by Step

有关RequireJS API更详细的指南清参看:http://requirejs.org/docs/api.html

通过RequireJS实现JavaScript的异步装载,首先得下载"require.js",地址:http://requirejs.org/

按照API文档,我们可以使用类似下面的目录规划:

  • www/
    • index.html
    • js/
      • app/
        • man.js
        • women.js
      • common
        • human.js
      • lib/
        • jquery.js
      • main.js
      • require.js

在index.html中加入下面内容引入"require.js"并指定入口js文件"app.js":

<script data-main="js/main.js" src="js/require.js"></script>

在human.js中添加以下内容:

define([], function() {
    return {
        sayHi: function() {
            console.log("human voice.");
        }
    }
});

在man.js中添加以下内容:

define(['common/human'], function(human) {
    return {
        sayHi: function() {
            human.sayHi();
            console.log("hi from man.");
        }
    }
});

在woman.js中添加以下内容:

define(['common/human'], function(human) {
    return {
        sayHi: function() {
            human.sayHi();
            console.log("hi from woman.");
        }
    }
});

在main.js中添加以下内容:

// main.js
console.log("main.js is loaded.");

requirejs.config({
    baseUrl: 'js/lib',
    paths: {
        app: '../app',
        common: '../common'
    }
});

require(['jquery', 'app/man', 'app/woman'], function($, man, woman) {
    $(document).ready(function() {
        console.log("document is ready.");
        
        man.sayHi();
        woman.sayHi();
    });
});

运行index.html我们可以在控制台看到如下信息:

main.js is loaded.
app.js:14 document is ready.
human.js:4 human voice.
man.js:5 hi from man.
human.js:4 human voice.
woman.js:5 hi from woman.

 

posted @ 2017-10-24 13:49  Jinzd  阅读(165)  评论(0编辑  收藏  举报