直播網(wǎng)站開發(fā)系統(tǒng)優(yōu)化的意義
main.js的介紹
main.js是在js模塊化編程二中對require.js的擴(kuò)展,一個項目通常是一個main.js,是整個網(wǎng)頁的入口代碼。它有點像C語言的main()函數(shù),所有代碼都從這兒開始運行。下面就來看,怎么寫main.js:
示例代碼如下:
/** main.js介紹說明:* baseUrl:config指定引用相對定位的其實路徑* paths:指定模塊引用的路徑,不包括.js,可以是一個目錄*/
require.config({baseUrl:getRootPath() + "/js",paths: {"jquery": "jquery-1.8.2","test": "test","gs-divtree": "gs.divtree"}
});//js獲取項目根路徑,如: http://localhost:8083/uimcardprj
function getRootPath() { //獲取當(dāng)前網(wǎng)址,如: http://localhost:8083/uimcardprj/share/meun.jsp var curWwwPath=window.document.location.href; //獲取主機(jī)地址之后的目錄,如: uimcardprj/share/meun.jsp var pathName=window.document.location.pathname; var pos=curWwwPath.indexOf(pathName); //獲取主機(jī)地址,如: http://localhost:8083 var localhostPaht=curWwwPath.substring(0,pos); //獲取帶"/"的項目名,如:/uimcardprj var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); return(localhostPaht+projectName);
}
test.js內(nèi)容如下:
define(function() {var add = function(x,y) {return (x+y);}return {add:add}
});
測試頁面如下:
<%@ page language="java" contentType="text/html; charset=utf-8"pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>index</title>
<!-- require方式引入加載的方式一二 -->
<script type="text/javascript" src="${pageContext.request.contextPath }/js/require.js" data-main="${pageContext.request.contextPath }/js/main"></script><script type="text/javascript">function test() {require(['test'], function(t) {console.log(t.add(1,6));});};
</script>
</head>
<body>require js <input id="test" type="button" value="test" name="test" οnclick="test();" />
</body>
</html>
此時該頁面只會加載test.js這個js文件,ps:若test.js需要用到其他的模塊該如何使用?
答案是有的 define定義的本身能引用其他模塊的,例如引用jquery:
//依賴于jquery模塊
define(['jquery'], function(b) {var add = function(x,y) {console.log(b("body"));return (x+y);}return {add:add}
});
更高級特性可以參考:http://www.requirejs.cn/ 中的內(nèi)容