最快实现跳转是用<meta http-equiv="refresh" content="0; url=/login.html">,纯HTML、零JS、兼容老IE;需放<head>中,0秒立即跳转,相对路径推荐用/login.html而非./login.html。
meta http-equiv="refresh" 最快实现跳转不需要 JavaScript,纯 HTML 就能搞定。浏览器原生支持,兼容性极好(包括老 IE),适合部署后临时重定向或维护页跳转。
在 index.html 的 <head> 里加这行:
<meta http-equiv="refresh" content="0; url=/login.html">
注意点:
content 值格式是 "秒数; url=目标地址",0 表示立即跳转/login.html)或完整 URL(如 https://example.com/app/),避免用 ./login.html,否则可能因当前 URL 路径层级出错window.location.href 跳转更可控适合需要判断条件、延迟执行、或记录日志的场景。比如用户已登录就跳首页,未登录则跳登录页。
立即学习“前端免费学习笔记(深入)”;
在 index.html 的 <body> 底部或 <script> 标签中写:
<script> // 立即跳转 window.location.href = '/dashboard.html'; // 或带简单判断 // if (localStorage.getItem('token')) { // window.location.href = '/dashboard.html'; // } else { // window.location.href = '/login.html'; // }</script>
注意点:
window.location.replace() 除非你明确不想让用户点「返回」回到 index.html —— 它会从历史栈删掉当前页DOMContentLoaded 或把 script 放在 body 底部如果你控制服务器(如 Nginx、Apache、Vercel、Cloudflare Pages),优先在服务端配置跳转。它更快、不依赖 JS、无白屏、且对爬虫友好。
常见配置示例:
location = /index.html { return 302 /app.html; }
vercel.json 中加 {"redirects": [{"source": "/index.html", "destination": "/app.html"}]}
服务端跳转的 HTTP 状态码建议用 302(临时)或 301(永久),别混用 —— 301 会被浏览器缓存,改错后难调试。
一是路径解析问题:浏览器对 url 参数的解析基于当前页面 URL,不是 HTML 文件物理位置。比如访问 https://site.com/sub/ 时打开 index.html,其中 url="login.html" 会跳到 https://site.com/sub/login.html,而非根目录。
二是移动端 WebView 场景:某些嵌入式 WebView(如微信内建浏览器、App 内置浏览器)可能拦截或延迟执行 meta refresh,此时必须用 window.location.href 才稳定。
真正上线前,务必用不同设备和网络环境实测跳转路径是否符合预期 —— 特别是带查询参数或哈希的 URL,稍不注意就会丢参或跳错。