一,hash路由:
window.onhashchange
二,history路由
history.go,history.back.history.forward使用popstate事件:window.onpopstate
pushState,replaceState需要通过函数重写方式进行劫持
const rawPushState = window.history.pushState
window.history.pushState = (...args) => {
rawPushState.apply(window.history,args)
}
const rawReplaceState = window.history.replaceState
window.history.replaceState = (...args) => {
rawReplaceState.apply(window.history,args)
}
其他问题记录:
为什么获取到dom或者html文本,直接通过document.querySelector("#id").innerHtml = html 运行后页面不会进行渲染?
1.客户端渲染需要通过执行JavaScript文件来生成内容
2.因为浏览器出于安全考虑innerHtml中的script不会加载执行
如何手动加载?
//1.获取所有script标签代码:[代码,代码,...]
function getExternalScripts(){
return Promise.all(Array.from(script).map(script => {
const src = script.getAttribute('src')
if(!src){
return Promise.resolve(scipte.innerHTML)
}else{
return fechResource(src.startsWith('http) ? src : `${url}${src}`)
}
}))
}
//2.执行所有script脚本代码
async function execScript(){
const scripts = await getExternalScripts()
//手动构造一个CommonJS模块环境
const module = {exports: {}}
const exports = module.exports
scripts.forEach(code => {
//eval执行的代码可以访问外部变量
eval(code)
})
return module.exports
}