此文已由作者杨介正授权网易云社区发布。
欢迎访问网易云社区,了解更多网易技术产品运营经验。
1.1 什么是history
h = {
//cross-platform add event to dom
_addEvent: function(dom, type, callback){
if('addEventListener' in window){
dom.addEventListener(type, callback, false);
}else{
dom.attachEvent('on' + type, callback);
}
},
_bind:function(fun, context){
return function(){
fun.apply(context, arguments);
}
},
_useHash: function(){
var
ua = /(msie)\s(\w+)/.exec(navigator.userAgent.toLowerCase());
return !ua || ua[2] > 7 && 'onhashchange' in window;
},
//get hash from url
_getHash: function(){
return /#\/?(.*)\/?/.exec(location.href)[1];
},
_doCallbacks: function(params){
console.log('here is callback')
},
_synHash: function(){
var
current = this._getHash(),
iHash = this.iWin ? this.iWin.location.hash.replace(/#/, '') : '',
old = this.iWin ? iHash : this.oldValue,
params;
old == undefined && (old = '');
if(current == old) return;
//prevent default behavior if the beforeChange method reutrn false
params = {
oldValue: old,
newValue: current
}
if(this.beforeChange(params) === false){
this.navigate(old);
return;
}
if(this.iWin){
//is navigation, create history entry
if(current != this.oldValue){
this.iWin.document.open();
this.iWin.document.close();
this.iWin.location.hash = current;
}
//just move history
else{
location.hash = iHash;
current = iHash;
params.newValue = iHash;
}
}
this._doCallbacks(params);
this.oldValue = current;
},
beforeChange: function(params){
return true
},
navigate: function(hash){
location.hash = hash;
},
bootstrap: function(){
var
iframe,
iWin;
if(!location.hash){
location.hash = '';
}
this.oldValue = this._getHash();
if(this._useHash()){
this._addEvent(window, 'hashchange', this._bind(this._synHash, this));
}else{
iframe = document.createElement('iframe');
iframe.src = 'javascript:void(0)';
iframe.style.display = 'none';
iframe.tabIndex = -1;
iWin = this.iWin = document.body.insertBefore(iframe, document.body.firstChild).contentWindow;
iWin.document.open();
//iWin.document.close();
iWin.location.hash = this._getHash();
this.timer = setInterval(this._bind(this._synHash, this), 50);
}
}
}
h.bootstrap()
网易云免费体验馆,0成本体验20+款云产品!
更多网易技术、产品、运营经验分享请点击。