一個簡單的前端路由實現(xiàn)

/*Returns thenumberof entries in the joint sessionhistory.*/

window .history. length

/*Returns the current state object.*/

window .history. state

/*Goes backorforward the specifiednumberof steps in the joint sessionhistory.A zero delta will reload the current page.If the deltaisout ofrange, does nothing.*/

window .history.go( [ delta ] )

/*Goes back one step in the joint sessionhistory.If thereisnopreviouspage, does nothing.*/

window .history. back()

/*Goes forward one step in the joint sessionhistory.If thereisnonextpage, does nothing.*/

window .history. forward()

/*Pushes the given data onto the sessionhistory, with the given title,and,ifprovidedandnot null, the given URL.*/

window .history. pushState(data, title [url] )

/*Updates the current entry in the sessionhistorytohave the given data, title,and,ifprovidedandnot null, URL.*/

window .history. replaceState(data, title [url] )

history.pushState和history.replaceState域那,這兩個history新增的api,為前端操控瀏覽器歷史棧提供了可能性


/***parameters

*@data{object} state對象败许,這是一個javascript對象淑蔚,一般是JSON格式的對象

*字面量。

*@title{string} 可以理解為document.title醋寝,在這里是作為新頁面?zhèn)魅雲(yún)?shù)的带迟。

*@url{string} 增加或改變的記錄,對應(yīng)的url嗅绰,可以是相對路徑或者絕對路徑,

*url的具體格式可以自定貌夕。

*/

history.pushState(data, title, url)//向瀏覽器歷史棧中增加一條記錄民镜。

history.replaceState(data, title, url)//替換歷史棧中的當(dāng)前記錄。

這兩個Api都會操作瀏覽器的歷史棧们童,而不會引起頁面的刷新鲸鹦。不同的是,pushState會增加一條新的歷史記錄齐板,而replaceState則會替換當(dāng)前的歷史記錄葛菇。所需的參數(shù)相同,在將新的歷史記錄存入棧后济舆,會把傳入的data(即state對象)同時存入莺债,以便以后調(diào)用。同時椎侠,這倆api都會更新或者覆蓋當(dāng)前瀏覽器的title和url為對應(yīng)傳入的參數(shù)侄旬。

來自mozilla有一個應(yīng)用pushState和replaceState小demo大家可以看一下:

varcurrentPage =5;// prefilled by server!!h邓小!

functiongo(d){? ? setupPage(currentPage + d);? ? history.pushState(currentPage,document.title,'?x='+ currentPage); }?

onpopstate =function(event){? ? setupPage(event.state); }

functionsetupPage(page){? ??

?currentPage = page;

document.title ='Line Game - '+ currentPage;

document.getElementById('coord').textContent = currentPage;

document.links[0].href ='?x='+ (currentPage+1);

document.links[0].textContent ='Advance to '+ (currentPage+1);

document.links[1].href ='?x='+ (currentPage-1);document.links[1].textContent ='retreat to '+ (currentPage-1); }

了解這倆api還不夠族操,再來看下上邊的demo中涉及到的popstate事件色难,我擔(dān)心解釋的不到位,所以看看mozilla官方文檔的解釋:


An eventhandlerforthe popstateeventonthe window.A popstateeventisdispatchedtothe window everytimethe active history entry changesbetweentwo history entriesforthe same document.Ifthe history entry being activated was createdbyacalltohistory.pushState()orwas affectedbyacalltohistory.replaceState(), the popstateevent's state property contains a copy of the history entry's state object.Note that justcallinghistory.pushState()orhistory.replaceState() won't trigger apopstate event. The popstate event is only triggered by doing a browser action such as clicking on the back button (or calling history.back() in JavaScript). And the event is only triggered when the user navigates between two history entries for the same document.

Browsers tend to handle the popstate event differently on page load. Chrome (prior to v34) and Safari always emit a popstate event on page load, but Firefox doesn't.Syntax? ?

?window.onpopstate = funcRef;? ? //funcRef is ahandlerfunction.

簡而言之娇昙,就是說當(dāng)同一個頁面在歷史記錄間切換時冒掌,就會產(chǎn)生popstate事件蹲盘。正常情況下,如果用戶點擊后退按鈕或者開發(fā)者調(diào)用:history.back() or history.go()铃诬,頁面根本就沒有處理事件的機(jī)會苍凛,因為這些操作會使得頁面reload。所以popstate只在不會讓瀏覽器頁面刷新的歷史記錄之間切換才能觸發(fā)毫深,這些歷史記錄一般由pushState/replaceState或者是由hash錨點等操作產(chǎn)生。并且在事件的句柄中可以訪問state對象的引用副本钉寝!而且單純的調(diào)用pushState/replaceState并不會觸發(fā)popstate事件闸迷。頁面初次加載時,知否會主動觸發(fā)popstate事件逮走,不同的瀏覽器實現(xiàn)也不一樣今阳。下邊是官方的一個demo:

window.onpopstate =function(event) {

?alert("location: "+ document.location +", state: "+? JSON.stringify(event.state));

};

history.pushState({page:1},"title 1","?page=1");

history.pushState({page:2},"title 2","?page=2");

history.replaceState({page:3},"title 3","?page=3");

history.back(); // alerts"location: http://example.com/example.html?page=1, state: {"page":1}"

history.back(); // alerts"location: http://example.com/example.html, state: null

history.go(2); // alerts "location: http://example.com/example.html?page=3, state: {"page":3}

H5還新增了一個hashchange事件盾舌,也是很有用途的一個新事件:

(function(window){// 如果瀏覽器不支持原生實現(xiàn)的事件,則開始模擬窿锉,否則退出。

if("onhashchange"inwindow.document.body ) {return; }

var location =window.location, oldURL = location.href, oldHash = location.hash;// 每隔100ms檢查hash是否發(fā)生變化

setInterval(function(){

varnewURL = location.href,? ? newHash = location.hash;// hash發(fā)生變化且全局注冊有onhashchange方法(這個名字是為了和模擬的事件名保持統(tǒng)一)窑多;

if( newHash != oldHash &&typeofwindow.onhashchange ==="function") {// 執(zhí)行方法

window.onhashchange({type:"hashchange",oldURL: oldURL,newURL: newURL? ? ? ? });? ? ? ??

?oldURL = newURL;? ? ? ? oldHash = newHash;? ? } },100);})(window);


更多 --->

淺析Web開發(fā)中前端路由實現(xiàn)的幾

Manipulating the browser history

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末埂息,一起剝皮案震驚了整個濱河市判沟,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌吧秕,老刑警劉巖迹炼,帶你破解...
    沈念sama閱讀 216,470評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件斯入,死亡現(xiàn)場離奇詭異,居然都是意外死亡刻两,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評論 3 392
  • 文/潘曉璐 我一進(jìn)店門滋迈,熙熙樓的掌柜王于貴愁眉苦臉地迎上來户誓,“玉大人,你說我怎么就攤上這事碍彭〉刻叮” “怎么了?”我有些...
    開封第一講書人閱讀 162,577評論 0 353
  • 文/不壞的土叔 我叫張陵漆枚,是天一觀的道長抵知。 經(jīng)常有香客問我刷喜,道長,這世上最難降的妖魔是什么初茶? 我笑而不...
    開封第一講書人閱讀 58,176評論 1 292
  • 正文 為了忘掉前任浊闪,我火速辦了婚禮,結(jié)果婚禮上折汞,老公的妹妹穿的比我還像新娘盖腿。我一直安慰自己,他們只是感情好翩腐,可當(dāng)我...
    茶點故事閱讀 67,189評論 6 388
  • 文/花漫 我一把揭開白布茂卦。 她就那樣靜靜地躺著,像睡著了一般处渣。 火紅的嫁衣襯著肌膚如雪而咆。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,155評論 1 299
  • 那天悠瞬,我揣著相機(jī)與錄音涯捻,去河邊找鬼障癌。 笑死,一個胖子當(dāng)著我的面吹牛涛浙,可吹牛的內(nèi)容都是我干的摄欲。 我是一名探鬼主播胸墙,決...
    沈念sama閱讀 40,041評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼按咒,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了智袭?” 一聲冷哼從身側(cè)響起掠抬,我...
    開封第一講書人閱讀 38,903評論 0 274
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎箫锤,沒想到半個月后雨女,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,319評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡馏臭,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,539評論 2 332
  • 正文 我和宋清朗相戀三年讼稚,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片帮寻。...
    茶點故事閱讀 39,703評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡赠摇,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出烫罩,到底是詐尸還是另有隱情,我是刑警寧澤洽故,帶...
    沈念sama閱讀 35,417評論 5 343
  • 正文 年R本政府宣布时甚,位于F島的核電站哈踱,受9級特大地震影響长捧,放射性物質(zhì)發(fā)生泄漏吻贿。R本人自食惡果不足惜串结,卻給世界環(huán)境...
    茶點故事閱讀 41,013評論 3 325
  • 文/蒙蒙 一肌割、第九天 我趴在偏房一處隱蔽的房頂上張望把敞。 院中可真熱鬧,春花似錦奋早、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至姓建,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間速兔,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評論 1 269
  • 我被黑心中介騙來泰國打工涣狗, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留屑柔,地道東北人。 一個月前我還...
    沈念sama閱讀 47,711評論 2 368
  • 正文 我出身青樓掸宛,卻偏偏與公主長得像唧瘾,于是被迫代替她去往敵國和親措译。 傳聞我的和親對象是個殘疾皇子饰序,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,601評論 2 353

推薦閱讀更多精彩內(nèi)容

  • 關(guān)于人生的思考求豫,常思常新,似乎每個階段都會對人生產(chǎn)生不同的理解蝠嘉。時代在變,我也在變蚤告,唯變不變。 人生如戲杜恰,戲如人生...
    過河鶇閱讀 435評論 2 5
  • 距離汶川大地震九年了檬寂,氣象臺說,今天這座城市格外晴朗桶至,夜晚有星光昼伴。 心靈一點一點破鏡重圓镣屹,城市一步一步復(fù)興繁榮。 ...
    南極的尾巴閱讀 737評論 0 2
  • 好的鏈接瀏覽器緩存過程瀏覽器緩存舉例 看完整理一份流程圖 舉個場景
    元氣滿滿321閱讀 703評論 1 3