相关文章推荐
奔跑的足球  ·  Document: ...·  6 月前    · 
俊秀的遥控器  ·  Exception has been ...·  9 月前    · 
动态修改document.title失效

动态修改document.title失效

背景: 如果页面title是异步获取的数据,那么拿到数据直接使用document.title会在ios低版本出现失效的问题,因为页面加载完成后title被确定,此后不再监听title的change事件

解决方法: 获取到数据后,动态创建iframe标签,src指向一个非常小的资源,监听load事件,加载完成立即删除即可更新title

代码:

      document.title = this.title;
      let iframe = document.createElement('iframe');
      iframe.src = require('/favicon.ico');
      iframe.style.display = 'none';
      let fn = function () {
        setTimeout(function () {
          iframe.removeEventListener('load', fn);
          document.body.removeChild(iframe);
          console.log('title', document.title);
        }, 0);
      iframe.addEventListener('load', fn);