seajs的使用--主要了解模块化

一个使用sea.js的Demo

sea.js可以解决命名问题,js文件间的依赖等.

index.html内容如下:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5     <title></title>
 6     <script src="../js/sea.js"></script>
 7 </head>
 8 <body>
 9     <script>
10         //jquery 1.8.2用不了.建议1.10.2以上.
11         seajs.config({
12             base: "/js/",
13             alias: { "jquery": "jquery-1.10.2.js" }
14         });
15 
16         seajs.use(['jquery', 'test'], function ($, test) {
17             $(document).ready(function () {
18                 test.doSomething('Jquery ready.');
19                 $("body").append('hello');
20             });
21         });
22 
23     </script>
24     <p id="p1"></p>
25 
26 
27     <script>
28         /*
29             恼人的命名冲突
30             在一个util.js文件里有function each(arr){...};function log(str){...};
31             一个页面在引用该util.js后,可能还有应用其他js文件,或者写该页面内部js脚本.
32             其他的js文件或者脚本可能也会命名each,log等方法,导致命名冲突,程序异常.
33         */
34         var ice = {};
35         ice.common = {};
36         ice.common.greet = function () {
37             alert('hello world!');
38         };
39 
40         (function (window) {
41             //此处的代码不会污染全局作用域
42 
43         })(window);
44     </script>
45 </body>
46 </html>
第16行: seajs.use(['jquery', 'test'], function ($, test) {...
需要加载 test.js,内容如下:
 1 define(function (require, exports, module) {
 2     //define(id,依赖,function())可以是3个参数
 3     //如:define('test', ['jquery'],function (require, exports, module) {
 4 
 5     // 通过 require 引入依赖
 6     // var $ = require('/js/jquery-1.10.2.js');
 7 
 8     // 通过 exports 对外提供接口
 9     exports.doSomething = function (str) {
10         alert(str);
11     };
12 
13     // 或者通过 module.exports 提供整个接口
14 });

附:seajs的学习网站

http://seajs.org/docs/

原文地址:https://www.cnblogs.com/ICE_Inspire/p/5213731.html