直播网站开发网站流量分析
main.js的介绍
main.js是在js模块化编程二中对require.js的扩展,一个项目通常是一个main.js,是整个网页的入口代码。它有点像C语言的main()函数,所有代码都从这儿开始运行。下面就来看,怎么写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() { //获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp var curWwwPath=window.document.location.href; //获取主机地址之后的目录,如: uimcardprj/share/meun.jsp var pathName=window.document.location.pathname; var pos=curWwwPath.indexOf(pathName); //获取主机地址,如: 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内容如下:
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/ 中的内容