DIV CSS 佈局教程網

SeaJS 完整示例:把知識點串成一個可運行的項目
編輯:JavaScript綜合知識     

前面分散講了不少 SeaJS 的概念,這篇直接用一個能跑起來的例子把它們串在一起,方便回頭歸納。

項目文件結構

  1. index.html——主頁面
  2. sea.js——SeaJS 腳本庫
  3. init.js——入口模塊,依賴 data、jquery、style 三個模塊,由主頁面載入
  4. data.js——純 JSON 數據模塊,由 init 載入
  5. jquery.js——對 jQuery 庫的模塊化封裝,由 init 載入
  6. style.css——CSS 樣式表,作為 style 模塊由 init 載入

sea.js 和 jquery.js 屬於庫代碼,這裡只列出自己編寫的部分。

HTML

<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <div id="content">
    <p class="author"></p>
    <p class="blog"><a href="#">Blog</a></p>
  </div>
  <script src="./sea.js" data-main="./init"></script>
</body>
</html>

注意最後一行:只引入 sea.js,並通過 data-main 屬性指定入口模塊。這等價於寫 seajs.use('./init'),但讓 HTML 更乾淨。

JavaScript

// init.js —— 入口模塊
define(function (require, exports, module) {
    var $    = require('./jquery');
    var data = require('./data');
    var css  = require('./style.css');

    $('.author').html(data.author);
    $('.blog').attr('href', data.blog);
});

// data.js —— 純數據模塊,直接傳對象給 define
define({
    author: 'ZhangYang',
    blog: 'https://blog.codinglabs.org'
});

CSS

.author { color: red; font-size: 10pt; }
.blog   { font-size: 10pt; }

這個例子示範了什麼

依賴聲明即依賴加載。init.js 裡沒有任何 <script> 標簽,也沒有手動排序,只靠 require 聲明依賴,SeaJS 就會自動按拓撲順序下載 jquery.js、data.js、style.css。頁面只需要關心「我要用什麼」,不用關心「別人什麼時候就緒」。

非 JS 資源也能模塊化。CSS 通過 require('./style.css') 載入,這體現了 SeaJS 「一切皆模塊」的思路。

數據也是模塊。data.js 只 return 一個對象,這種寫法特別適合存放配置和常量。

項目規模一大,這種方式的價值會被放大:新增一個依賴只需在模塊裡加一行 require,不必回到 HTML 裡找插入位置,也不必擔心順序錯了導致某個變量是 undefined。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved