如何让window.open新标签页优先显示加载图标?MVC视图加载前加载器问题
解决新标签页先显示加载器的问题
这个问题其实是因为你监听的是当前页面的readyState,和新打开的标签页完全不搭边~ 新标签页在加载MVC视图的HTML时,浏览器得先下载完整个HTML文件才会开始解析里面的脚本,这中间就会出现空白期。要让加载器成为新标签页的第一个元素,得换个思路:在新窗口打开后,立刻往里面写入加载器的HTML,再去加载目标Action。
下面给你两种可行的方案:
方案一:直接写入加载器后跳转目标Action
这种方式最直接,打开新窗口后立刻渲染加载器,再跳转到你的MVC视图,视图加载完成后会自动替换掉加载器页面。
// 打开空白新窗口 const newWindow = window.open('', '_blank'); // 立即写入带加载器的基础HTML,这会成为新标签页的第一个显示内容 newWindow.document.write(` <!DOCTYPE html> <html> <head> <style> .loader { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 8px solid #f3f3f3; border-top: 8px solid #3498db; border-radius: 50%; width: 60px; height: 60px; animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } body { margin: 0; padding: 0; background-color: #fff; } </style> </head> <body> <div class="loader"></div> </body> </html> `); newWindow.document.close(); // 关闭写入流,触发浏览器立即渲染加载器 // 跳转到你的MVC Action newWindow.location.href = '/YourController/YourAction';
方案二:用iframe加载页面,加载完成后替换加载器
如果你的MVC视图包含大量资源(图片、脚本等),想让加载器一直显示到页面完全就绪,可以用这种方式:
const newWindow = window.open('', '_blank'); newWindow.document.write(` <!DOCTYPE html> <html> <head> <style> .loader { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); border: 8px solid #f3f3f3; border-top: 8px solid #3498db; border-radius: 50%; width: 60px; height: 60px; animation: spin 1s linear infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } body, html { margin: 0; padding: 0; height: 100%; } iframe { width: 100%; height: 100%; border: none; display: none; } </style> </head> <body> <div class="loader" id="loader"></div> <iframe id="targetFrame" src="/YourController/YourAction"></iframe> <script> const frame = document.getElementById('targetFrame'); const loader = document.getElementById('loader'); // 监听iframe加载完成事件,隐藏加载器显示页面 frame.onload = function() { loader.style.display = 'none'; frame.style.display = 'block'; }; </script> </body> </html> `); newWindow.document.close();
注意事项
- 替换代码中的
/YourController/YourAction为你实际的MVC Action路径; - 加载器的样式可以根据你的项目风格自定义(颜色、大小、动画等);
- 确保你的MVC项目和当前页面是同域的,否则可能会遇到跨域权限问题。
内容的提问来源于stack exchange,提问作者Manjay_TBAG
相关产品推荐
相关产品推荐

