工程介绍
requireSPA,require.js和它的一个插件text.js实现简单SPA测试
工程目录
源码及分析
index.html
入口html,加载requirejs,同时指定主模块
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<style type="text/css" class="css-attribute">
</style>
</head>
<body>
<script data-main="js/main" src="js/require.js"></script>
<div class="page">
</div>
</body>
</html>
require.js
RequireJS 2.2.0
lib/jquery.js lib/text
本地存放的jquery.js 文件 已经requirejs的text.文件
* jQuery JavaScript Library v1.11.0
* http://jquery.com/
RequireJS text 2.0.14
template test1.html test2.html 对应2个页面
test1.html
<div class="test1">
<button class="skip">点击我跳到SPA第二页</button>
</div>
test2.thml
<div class="test2">
<button class="skip2">我是第二页,点击我回第一页</button>
</div>
test1.css test2.css 2个页面对应的样式css
test1.css
.test1{
position: absolute;
top:0;
bottom:0;
left: 0;
right: 0;
background-color: red;
}
.skip{
position: absolute;
top:50%;
left: 50%;
-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
test2.css
.test2{
position: absolute;
top:0;
bottom:0;
left: 0;
right: 0;
background-color: pink;
}
.skip2{
position: absolute;
top:50%;
left: 50%;
-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
主模块main.js
require.config定义了引用模块的路径,以及资源文件test.html test.css
在index.html首页 渲染 test1.html
页面加载好之后绑定跳转事件
跳转事件是把页面文档换成test2.html
这里没有路由功能,不能从1->2,2->1后,再次从1->2
只是简单实用amd异步加载require.js,以及使用插件 text
require.config({
paths:{
"jquery":"lib/jquery-1.11.0",
"text":"lib/text",
"text1":"../template/test1.html", //这里千万注意路径
"text2":"../template/test2.html",
"css1":"../style/test1.css",
"css2":"../style/test2.css"
}
})
require(['jquery','text!text1','text!text2','text!css1','text!css2'],function($,template1,template2,css1,css2){
// 进入页面先设置为页面test1.html内容
$(".css-attribute").html(css1);
$(".page").html(template1);
// 点击skip按钮设置为页面test2.html内容
$(".skip").click(function(){
$(".css-attribute").html(css2);
$(".page").html(template2);
setTimeout(function (){
// 点击skip按钮设置为页面test2.html内容
$(".skip2").click(function(){
$(".css-attribute").html(css1);
$(".page").html(template1);
})
},1000)
})
})