启动画面
如果您的网页加载时间较长,或者您需要在显示主窗口之前在 Rust 中运行初始化过程,启动画面可以改善用户的加载体验。
设置
首先,在您的 `distDir` 中创建一个 `splashscreen.html` 文件,其中包含启动画面的 HTML 代码。请注意,如果您在基于 Vite 的项目中使用 Tauri,建议在项目的 `public` 文件夹中,紧挨着 `package.json` 创建 `splashscreen.html`。
然后,像这样更新您的 `tauri.conf.json`
"windows": [
{
"title": "Tauri App",
"width": 800,
"height": 600,
"resizable": true,
"fullscreen": false,
+ "visible": false // Hide the main window by default
},
// Add the splashscreen window
+ {
+ "width": 400,
+ "height": 200,
+ "decorations": false,
+ "url": "splashscreen.html",
+ "label": "splashscreen"
+ }
]
现在,启动应用程序时,您的主窗口将被隐藏,而启动画面窗口将显示。接下来,您需要一种方法来关闭启动画面并在应用程序准备好后显示主窗口。如何做到这一点取决于您在关闭启动画面之前等待的内容。
等待网页加载
如果您正在等待网页代码加载,您需要创建一个 `close_splashscreen` 命令。
use tauri::{Manager, Window};
// Create the command:
// This command must be async so that it doesn't run on the main thread.
#[tauri::command]
async fn close_splashscreen(window: Window) {
// Close splashscreen
window.get_window("splashscreen").expect("no window labeled 'splashscreen' found").close().unwrap();
// Show main window
window.get_window("main").expect("no window labeled 'main' found").show().unwrap();
}
// Register the command:
fn main() {
tauri::Builder::default()
// Add this line
.invoke_handler(tauri::generate_handler![close_splashscreen])
.run(tauri::generate_context!())
.expect("failed to run app");
}
您可以通过以下两种方式之一将其导入到您的项目中
// With the Tauri API npm package:
import { invoke } from '@tauri-apps/api/tauri'
或者
// With the Tauri global script:
const invoke = window.__TAURI__.invoke
最后,添加一个事件监听器(或者在您需要时调用 `invoke()`)
document.addEventListener('DOMContentLoaded', () => {
// This will wait for the window to load, but you could
// run this function on whatever trigger you want
invoke('close_splashscreen')
})
等待 Rust 代码执行
如果您正在等待 Rust 代码运行,请将其放在 `setup` 函数处理程序中,以便您可以访问 `App` 实例
use tauri::Manager;
fn main() {
tauri::Builder::default()
.setup(|app| {
let splashscreen_window = app.get_window("splashscreen").unwrap();
let main_window = app.get_window("main").unwrap();
// we perform the initialization code on a new task so the app doesn't freeze
tauri::async_runtime::spawn(async move {
// initialize your app here instead of sleeping :)
println!("Initializing...");
std::thread::sleep(std::time::Duration::from_secs(2));
println!("Done initializing.");
// After it's done, close the splashscreen and display the main window
splashscreen_window.close().unwrap();
main_window.show().unwrap();
});
Ok(())
})
.run(tauri::generate_context!())
.expect("failed to run app");
}