RequireJS Step by Step

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

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

按照API文档,咱们可使用相似下面的目录规划: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":app

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

在human.js中添加如下内容:异步

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

在man.js中添加如下内容:requirejs

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

在woman.js中添加如下内容:ui

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

在main.js中添加如下内容:
spa

// 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咱们能够在控制台看到以下信息:code

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.
相关文章
相关标签/搜索