银川网站制作,家装公司网站,专业网站seo推广,wordpress全局透明主题main.js的介绍 main.js是在js模块化编程二中对require.js的扩展#xff0c;一个项目通常是一个main.js,是整个网页的入口代码。它有点像C语言的main()函数#xff0c;所有代码都从这儿开始运行。下面就来看#xff0c;怎么写main.js: 示例代码如下#xff1a; /** main.js介…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 curWwwPathwindow.document.location.href; //获取主机地址之后的目录如 uimcardprj/share/meun.jsp var pathNamewindow.document.location.pathname; var poscurWwwPath.indexOf(pathName); //获取主机地址如 http://localhost:8083 var localhostPahtcurWwwPath.substring(0,pos); //获取带/的项目名如/uimcardprj var projectNamepathName.substring(0,pathName.substr(1).indexOf(/)1); return(localhostPahtprojectName);
} test.js内容如下 define(function() {var add function(x,y) {return (xy);}return {add:add}
}); 测试页面如下 % page languagejava contentTypetext/html; charsetutf-8pageEncodingutf-8%
!DOCTYPE html PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN http://www.w3.org/TR/html4/loose.dtd
html
head
titleindex/title
!-- require方式引入加载的方式一二 --
script typetext/javascript src${pageContext.request.contextPath }/js/require.js data-main${pageContext.request.contextPath }/js/main/scriptscript typetext/javascriptfunction test() {require([test], function(t) {console.log(t.add(1,6));});};
/script
/head
bodyrequire js input idtest typebutton valuetest nametest οnclicktest(); /
/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 (xy);}return {add:add}
}); 更高级特性可以参考http://www.requirejs.cn/ 中的内容