模組化JS編程 seajs簡單例子

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   strong   

 

1.引入sea.js

test.html

 

 1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>My Frist SeaJs</title> 6 </head> 7 <body> 8 <div id="container"> 9  10 </div>11 12 <script src="../sea-modules/seajs/seajs/2.2.0/sea.js"></script>13 <script>14 15   // Set configuration16     seajs.config({17          alias: {18              "jquery": "../script/jquery-1.11.1"19         }20     });21 22   seajs.use("../script/mysea.js");23 </script>24 25 </body>26 </html>

 

2.定義mysea.js

mysea.js

 

1 define(function (require, exports, module) {
//獲得依賴2 var mysea2 = require(‘../script/mysea2‘);3 mysea2.show();4 });

 

2.定義mysea2.js

mysea2.js

 

1 define(function (require, exports, module) {
//暴露show介面2 exports.show = function() {3 alert(‘mysea2‘);4 };5 });

 

輸出結果:

 

 

模組化編程的目的很明顯,我們不在像以前那樣function(),function()的編寫代碼.我們可以很自由的組織代碼,可避免一些代碼衝突.

這裡有個小問題,demo 引用的是jquery-1.11.1.由於jquery遵循是AMD規範. 在seajs官網的例子運行是沒有問題的,因為作了修改(seajs是CMD規範).

所以jquery-1.11.1也做了修改,否則依賴的jquery會找不到的.

 

jquery-1.11原本的定義

1 if (typeof define === "function" && define.amd) {2         define("jquery", [], function () {3         return jQuery;4    });5 }

 

修改如下

1 if (typeof define === "function") {
//合理的路徑2 define("../script/jquery-1.11.1", [], function () { return jQuery; });3 }

 

關於規範

AMD規範:https://github.com/amdjs/amdjs-api/wiki/AMD

seajs模組定義規範:https://github.com/seajs/seajs/issues/242

 

 

下載seajshttps://github.com/seajs/seajs/releases 官網http://seajs.org/docs/ 
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.