【vue.js之夯实基础-9】Javascript模块化编程 require.js应用实战 requireSPA,创建一个spa单页应用依赖模块(jquery,text-加载html,css)

工程介绍

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)
	})

})


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值