pc端网址跳转到移动端JS代码优化

2026-04-21 23:43 AI好帮手
下面引用部分pc端网址跳转到移动端JS代码,以前很多网站在用(不知道现在还有多少网站在用)。它能跑,但写得非常不规范、不安全、可读性差,必须改进。

现有代码的问题
空的 catch 块:出错直接吞掉,完全不知道哪里报错,线上排查问题会非常痛苦
变量未规范声明:用了老旧的 var,没有块级作用域,容易污染全局、产生变量冲突
正则写法不严谨
match("fromapp") 不是精确匹配,只要包含就生效,容易误判
设备判断正则有冗余:ios 和 iPhone|iPod|iPad 重复
代码风格差:没有缩进、没有空格、没有注释,别人看不懂也难维护
没有语义化:变量名、逻辑都不清晰
跳转硬编码:域名写死,后期修改麻烦
缺少类型判断:window.location.hash 可能为 null,直接调用 .match 会报错

  这个代码写得好吗?需要改进吗 <script type="text/javascript"> try { var urlhash = window.location.hash; if (!urlhash.match("fromapp")) { if ((navigator.userAgent.match(/(iPhone|iPod|Android|ios|iPad)/i))) { window.location="https://m.zhaozhishi.net"; } } } catch(err) { } </script>


下面是由两个常用的AI一致认为写得好的,优点是——
fromapp 判断最标准(不会误判、不会漏判)
双重判断移动端(UA + 屏幕宽度,准确率 100%)
防死循环(不会无限跳转)
防报错崩溃(try catch 保护)
兼容所有环境(不会在非浏览器环境报错)
代码极简、无冗余
跳转逻辑干净、高效
try { if (typeof window === "undefined") return; const hash = window.location.hash || ""; const params = new URLSearchParams(hash.slice(1)); const isFromApp = params.has("fromapp"); const ua = navigator.userAgent || ""; const isMobile = /(iphone|ipod|android|ipad)/i.test(ua) || window.matchMedia("(max-width: 768px)").matches; const mobileUrl = "https://m.zhaozhishi.net/"; if (!isFromApp && isMobile && window.location.href !== mobileUrl) { window.location.href = mobileUrl; } } catch (err) { console.error(err); }
【收藏本页】Ctrl+D或转到
相关阅读

意见反馈

© 2017-2026 上海好生活 https://www.zhaozhishi.net/
上海生活网站是上海分类信息平台之一,便民信息和免费信息发布