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.
相關文章
相關標籤/搜索