使用window.open()跳转页面出现反复重载问题的解决方案问询
问题原因
- 你当前每个适配页(
index.html/mobile.html/tablet.html)都引入了这段跳转逻辑,页面跳转后重新加载脚本,会再次触发尺寸判断、重复跳转当前页面,就出现了反复重载的问题。 - 另外用
window.open指定_self本身和直接修改location行为一致,属于没必要的冗余写法,还可能触发部分浏览器的弹窗拦截逻辑。
修复方案
方案1:添加跳转判断标识,避免重复跳转
在跳转前先判断当前页面是否已经是目标适配页,是的话就不执行跳转:
function redirect() { // 先获取当前页面路径,判断是否已经是目标页 const currentPage = window.location.pathname.split('/').pop(); let deviceWidth = document.documentElement.clientWidth; if ((deviceWidth > 320) && (deviceWidth < 720 )) { if(currentPage === 'mobile.html') return; // 已经是移动端页,不跳转 mobile(); } else if ((deviceWidth >= 720) && (deviceWidth < 1200)) { if(currentPage === 'tablet.html') return; // 已经是平板页,不跳转 tablet(); } else if (deviceWidth >= 1200) { if(currentPage === 'index.html' || currentPage === '/') return; // 已经是桌面端页,不跳转 desktop(); } else { console.log("something wrong"); } function mobile() { window.location.replace("./mobile.html"); console.log('mobile'); } function tablet() { window.location.replace("./tablet.html"); console.log('tablet'); } function desktop() { window.location.replace("./index.html"); console.log('desktop'); } } redirect();
方案2:更优的响应式适配方案(无需多页跳转)
如果不是业务强制要求分多端页面,优先用响应式布局实现适配,完全规避跳转逻辑带来的问题:
- 用CSS媒体查询
@media针对不同宽度阈值写不同的布局样式 - 少量需要JS适配的逻辑也可以配合
matchMediaAPI做动态调整,不需要页面跳转,体验更好
额外优化点
- 可以加防抖逻辑,避免用户手动拖拽窗口宽度的时候频繁触发跳转
- 上面的代码已经调整了尺寸阈值的边界判断,覆盖了原来漏判的720px、1199px等临界尺寸,不会再出现边界宽度触发报错的问题
内容的提问来源于stack exchange,提问作者Muhammad Owais
相关产品推荐
相关产品推荐

