原因就是:瀏覽器首次加載頁面初始化title后,就再也不監聽 document.title的change事件,因此只使用document.title來修改,不會有效果。
解決辦法:修改了title后,立即創建一個請求,加載一個空的iframe,由於加載后立即就移除,也不會對頁面造成影響,但這樣瀏覽器上的title便刷新了。
const setDocumentTitle = function(title) {
document.title = title;
if (/ip(hone|od|ad)/i.test(navigator.userAgent)) {
var i = document.createElement('iframe');
i.src = '/favicon.ico';
i.style.display = 'none';
i.onload = function() {
setTimeout(function(){
i.remove();
}, 9)
}
document.body.appendChild(i);
}
}
router.afterEach((to, from, next) => {
const { title } = to.meta;
if(title && document.title!=title) setDocumentTitle(title);
})
display:none這個設置使iframe脫離文本流,那么加載和刪除這個iframe都不會改變文本流,也不會觸發頁面渲染,性能會好一些。