require簡(jiǎn)單實(shí)現(xiàn)單頁(yè)應(yīng)用程序(SPA)
寫(xiě)了一個(gè)測(cè)試代碼,用require.js配合它的一個(gè)插件text.js實(shí)現(xiàn)了最簡(jiǎn)單的單頁(yè)應(yīng)用程序,簡(jiǎn)單的記錄一下,方便以后復(fù)習(xí),
git地址:https://github.com/lily1010/requireSPA
下面來(lái)看一下目錄

從上面項(xiàng)目可以看出,我將css單獨(dú)抽離出去,實(shí)現(xiàn)了按需加載,即加載test1.html時(shí)會(huì)加載test1.css,加載test2.html時(shí)會(huì)加載test2.css.
一 先來(lái)看入口index.html代碼
<!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>
上面很簡(jiǎn)單,先定義requirejs入口data-main,另外為了按需加載css,我定義了一個(gè)類css-attribute.
二 在main.js配置路徑和做邏輯處理
require.config({
paths:{
"jquery":"lib/jquery-1.11.0",
"text":"lib/text",
"text1":"../template/test1.html", //這里千萬(wàn)注意路徑
"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){
// 進(jìn)入頁(yè)面先設(shè)置為頁(yè)面test1.html內(nèi)容
$(".css-attribute").html(css1);
$(".page").html(template1);
// 點(diǎn)擊skip按鈕設(shè)置為頁(yè)面test2.html內(nèi)容
$(".skip").click(function(){
$(".css-attribute").html(css2);
$(".page").html(template2);
})
})
上面都是最基礎(chǔ)的require配置,注意text.js用法就可以了,很簡(jiǎn)單的
三 來(lái)看看2個(gè)頁(yè)面結(jié)構(gòu)以及樣式
①test1.html代碼如下:
<div class="test1"> <button class="skip">點(diǎn)擊我跳到SPA第二頁(yè)</button> </div>
②test1.html的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%);
}
實(shí)現(xiàn)效果如下:

③test2.html代碼如下:
<div class="test2"> <button class="skip2">我是第二頁(yè),點(diǎn)擊我回第一頁(yè)</button> </div>
④test2.html的css,即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%);
}
實(shí)現(xiàn)效果如下:

以上這篇require簡(jiǎn)單實(shí)現(xiàn)單頁(yè)應(yīng)用程序(SPA)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
php常見(jiàn)的頁(yè)面跳轉(zhuǎn)方法匯總
Web系統(tǒng)中,從一個(gè)網(wǎng)頁(yè)跳轉(zhuǎn)到另一個(gè)網(wǎng)頁(yè),是LAMP項(xiàng)目中最常用的技術(shù)之一。頁(yè)面跳轉(zhuǎn)可能是由于用戶單擊鏈接、按鈕等引發(fā)的,也可能是系統(tǒng)自動(dòng)產(chǎn)生的。 此處介紹PHP中常用的實(shí)現(xiàn)頁(yè)面自動(dòng)跳轉(zhuǎn)的方法。2015-04-04
javascript Prototype 對(duì)象擴(kuò)展
從對(duì)象創(chuàng)建一個(gè)實(shí)例說(shuō)起來(lái)貌似是很簡(jiǎn)單的東西,是啊,基本在所有的語(yǔ)言中,都是用new關(guān)鍵字來(lái)創(chuàng)建實(shí)例的2009-05-05
Javascript實(shí)現(xiàn)簡(jiǎn)單的富文本編輯器附演示
這篇文章主要介紹了通過(guò)Javascript實(shí)現(xiàn)的簡(jiǎn)單富文本編輯器,需要的朋友可以參考下2014-06-06
跨瀏覽器開(kāi)發(fā)經(jīng)驗(yàn)總結(jié)(四) 怎么寫(xiě)入剪貼板
讓你的操作剪切板的操作支持多瀏覽器,一般IE,Firefox2010-05-05

