使用iframe搭建微前端

var ISPA = function(options){
 var _this = this
  
 this.callback = options.callback || new Function
 this.hash
 this.prefix = options.prefix || ''
 this.anchor = options.anchor || 'data-anchor'
 this.iframe = typeof options.iframe == 'string'? document.getElementById(options.iframe) : iframe
  
 this.defaultHash = options.defaultHash
 this.hash = this.getHash()
  
 this.handler(this.hash, true)
  
 if (!('onhashchange' in document.body)){
 throw new Error('is onhashchange not supported')
 }
  
  
  
 function poll(){
 var currHash = _this.getHash()
 if (currHash != _this.hash){
 _this.hash = currHash
 _this.handler(currHash, false)
 }
 }
  
 this.addEvent(window, 'hashchange', poll)
 this.bindEvents()
  
 }
  
 ISPA.prototype.addEvent = function(ele, type, callback){
 if (ele.addEventListener){
 ele.addEventListener(type, callback)
 }else if(ele.attachEvent){
 ele.attachEvent('on' + type, callback)
 }
 }
  
 ISPA.prototype.handler = function(newHash, init){
 if (this.callback(this, init) == false){
 return
 }
 var url
 var hash = newHash || this.defaultHash
 hash.replace(/\/+/g, '/')
  
 url = window.location.protocol + '//' + window.location.host + this.prefix + hash
 this.iframe.contentWindow.location.replace(url)
 }
 ISPA.prototype.bindEvents = function(){
 var _this = this
 this.addEvent(document, 'click', function(e){
  
 e = e || window.event
 el = e.target || e.srcElement
 if (el.tagName.toLowerCase() != 'a'){
 return
 }
 if (el.getAttribute(_this.anchor) != null){
 e.preventDefault ? e.preventDefault() : (e.returnValue = false)
  
 var hash = el.getAttribute('href')
 hash = hash.replace(/\/+/g, '/').replace(/(java|vb)script/g,'')
 window.location.hash = hash
 }
 })
 }
  
 ISPA.prototype.go = function(newHash){
 if (newHash == this.hash) {
 return
 }
 window.location.hash = this.hash = newHash
 this.hanlder(newHash, false)
  
 }
 ISPA.prototype.getHash = function(){
 var index = window.location.href.indexOf('#')
 return (index == -1? '' : window.location.href.substr(index + 1))
 }
  

 

 

用法

new ISPA({
  callback: '',
  defaultHash: '',
  prefix: '',
  anchor: '',
  iframe: 'iframe' //必选
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值