Sum*_*Dey 9 javascript dom reactjs server-side-rendering next.js
如何显示我自己的加载程序而不是空白屏幕?例如,Tweeter 在页面加载时显示徽标,对于 Facebook、Google AdSense 等也是如此。看看这个 Gif,我想要在 Next Js 中出现类似的内容。
我想这与 _document.js 有关。React js 有一个类似的问题(在 index.html 中渲染加载器),但我不知道如何在下一个 js 中做到这一点。
小智 9
要在 Nextjs 上添加启动屏幕,您可以通过多种方式完成。这是我首选的解决方案。
/**
* inside _app.js function for remove the loader
*/
useEffect(() => {
if (typeof window !== 'undefined') {
const loader = document.getElementById('globalLoader');
if (loader)
loader.remove();
}
}, []);Run Code Online (Sandbox Code Playgroud)
/* Style.css or global.css */
#globalLoader {
position: fixed;
z-index: 9999;
top: 50%;
left: 50%;
background-color: #fff;
transform: translate(-50%, -50%);
width: 100%;
height: 100%;
justify-content: center;
align-items: center;
display: flex;
}Run Code Online (Sandbox Code Playgroud)
/** * on _document.js insert below code after body tag * More about _document.js -> https://nextjs.org/docs/advanced-features/custom-document */
<div id="globalLoader">
<img src="https://upload.wikimedia.org/wikipedia/commons/b/b1/Loading_icon.gif" alt="" />
</div>Run Code Online (Sandbox Code Playgroud)
小智 5
如果您使用的是 next js 13 应用程序路由器,您可以简单地添加一个“loading.js”(如果您将此文件命名为任何其他名称,它将不起作用,它应该是由 next.js 保留的 loading.js || ts)文件app 文件夹并添加您想要的任何类型的加载动画或图像。
通常这些是通过一个覆盖所有内容并默认显示的 div 来完成的,您在该 div 中放置的内容取决于您(gif、svg 等)。一旦 window.onload 被调用,只需隐藏 div,它将显示完全渲染的 dom。
这是一个基本示例(我在移动设备上,请原谅我的格式)CSS:
.loadingsScreen{
position:absolute;
left:0;
top:0;
width:100%;
height:100%;
background-color: #whatever-color;
z-index: 10; /*just make sure it's the highest on the page*/
}
Run Code Online (Sandbox Code Playgroud)
JS:
window.onload = function(){
$("#loadingScreen").fadeOut(); //just make it hide the overlaying div, I used jQuery in this example but there are many ways to do this
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28971 次 |
| 最近记录: |