启动画面
在本实验中,我们将为一个 Tauri 应用实现基本的启动屏幕功能。实现过程非常直观:启动屏幕本质上只是创建一个新窗口,在应用执行繁重的设置任务期间显示一些内容,并在设置完成后将其关闭。
-
在开始开发任何项目之前,构建并运行初始模板非常重要,这可以验证你的设置是否按预期工作。
# Make sure you're in the right directorycd splashscreen-lab# Install dependenciespnpm install# Build and run the apppnpm tauri dev
-
添加新窗口最简单的方法是直接将它们添加到
tauri.conf.json中。你也可以在启动时动态创建它们,但为了简单起见,我们选择注册它们。请确保你有一个标签为main的窗口,它在创建时处于隐藏状态;还有一个标签为splashscreen的窗口,在创建时直接显示。你可以将所有其他选项保留为默认值,或者根据偏好进行调整。src-tauri/tauri.conf.json {"windows": [{"label": "main","visible": false},{"label": "splashscreen","url": "/splashscreen"}]} -
在开始之前,你需要准备一些内容来展示。开发新页面的方式取决于你选择的框架,大多数框架都有处理页面导航的“路由”概念,这在 Tauri 中应该可以像往常一样工作,在这种情况下,你只需创建一个新的启动屏幕页面即可。或者,正如我们此处将要做的那样,创建一个新的
splashscreen.html文件来托管这些内容。这里重要的是,你可以导航到
/splashscreenURL 并显示你想要的启动屏幕内容。在此步骤之后,尝试再次运行该应用程序!/splashscreen.html <!doctype html><html lang="en"><head><meta charset="UTF-8" /><link rel="stylesheet" href="/src/styles.css" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Tauri App</title></head><body><div class="container"><h1>Tauri used Splash!</h1><div class="row"><h5>It was super effective!</h5></div></div></body></html>
-
由于启动屏幕通常旨在隐藏繁重的设置任务,让我们模拟一下让应用做一些繁重的工作,部分在前端,部分在后端。
为了模拟前端的繁重设置,我们将使用一个简单的
setTimeout函数。在后端模拟繁重操作最简单的方法是使用 Tokio crate,这是 Tauri 在后端使用的 Rust crate,用于提供异步运行时。虽然 Tauri 提供了该运行时,但有些工具函数 Tauri 并没有重新导出,因此我们需要将该 crate 添加到我们的项目中才能访问它们。这在 Rust 生态系统中是一种非常常见的做法。
不要在异步函数中使用
std::thread::sleep,因为它们在并发环境中是协作式运行的,而不是并行运行的。这意味着如果你休眠了线程而不是 Tokio 任务,你将阻塞所有调度在该线程上运行的任务,导致你的应用冻结。# Run this command where the `Cargo.toml` file iscd src-tauri# Add the Tokio cratecargo add tokio -F time# Optionally go back to the top folder to keep developing# `tauri dev` can figure out where to run automaticallycd ..src/main.ts // These contents can be copy-pasted below the existing code, don't replace the entire file!!// Utility function to implement a sleep function in TypeScriptfunction sleep(seconds: number): Promise<void> {return new Promise(resolve => setTimeout(resolve, seconds * 1000));}// Setup functionasync function setup() {// Fake perform some really heavy setup taskconsole.log('Performing really heavy frontend setup task...')await sleep(3);console.log('Frontend setup task complete!')// Set the frontend task as being completedinvoke('set_complete', {task: 'frontend'})}// Effectively a JavaScript main functionwindow.addEventListener("DOMContentLoaded", () => {setup()});/src-tauri/src/lib.rs // Import functionalities we'll be usinguse std::sync::Mutex;use tauri::async_runtime::spawn;use tauri::{AppHandle, Manager, State};use tokio::time::{sleep, Duration};// Create a struct we'll use to track the completion of// setup related tasksstruct SetupState {frontend_task: bool,backend_task: bool,}// Our main entrypoint in a version 2 mobile compatible app#[cfg_attr(mobile, tauri::mobile_entry_point)]pub fn run() {// Don't write code before Tauri starts, write it in the// setup hook instead!tauri::Builder::default()// Register a `State` to be managed by Tauri// We need write access to it so we wrap it in a `Mutex`.manage(Mutex::new(SetupState {frontend_task: false,backend_task: false,}))// Add a command we can use to check.invoke_handler(tauri::generate_handler![greet, set_complete])// Use the setup hook to execute setup related tasks// Runs before the main loop, so no windows are yet created.setup(|app| {// Spawn setup as a non-blocking task so the windows can be// created and ran while it executesspawn(setup(app.handle().clone()));// The hook expects an Ok resultOk(())})// Run the app.run(tauri::generate_context!()).expect("error while running tauri application");}#[tauri::command]fn greet(name: String) -> String {format!("Hello {name} from Rust!")}// A custom task for setting the state of a setup task#[tauri::command]async fn set_complete(app: AppHandle,state: State<'_, Mutex<SetupState>>,task: String,) -> Result<(), ()> {// Lock the state without write accesslet mut state_lock = state.lock().unwrap();match task.as_str() {"frontend" => state_lock.frontend_task = true,"backend" => state_lock.backend_task = true,_ => panic!("invalid task completed!"),}// Check if both tasks are completedif state_lock.backend_task && state_lock.frontend_task {// Setup is complete, we can close the splashscreen// and unhide the main window!let splash_window = app.get_webview_window("splashscreen").unwrap();let main_window = app.get_webview_window("main").unwrap();splash_window.close().unwrap();main_window.show().unwrap();}Ok(())}// An async function that does some heavy setup taskasync fn setup(app: AppHandle) -> Result<(), ()> {// Fake performing some heavy action for 3 secondsprintln!("Performing really heavy backend setup task...");sleep(Duration::from_secs(3)).await;println!("Backend setup task completed!");// Set the backend task as being completed// Commands can be ran as regular functions as long as you take// care of the input arguments yourselfset_complete(app.clone(),app.state::<Mutex<SetupState>>(),"backend".to_string(),).await?;Ok(())} -
现在你应该看到启动屏幕窗口弹出,前端和后端将分别执行各自 3 秒钟的繁重设置任务,之后启动屏幕消失,主窗口显示出来!
通常来说,使用启动屏幕是一种“妥协”的承认,意味着你无法让应用加载得足够快而无需它。事实上,通常更好的做法是直接进入主窗口,然后在某个角落显示一个小转轮,通知用户后台仍在进行设置任务。
话虽如此,这也可以是一种风格选择,或者你可能有某些特殊需求,导致在完成某些任务之前无法启动应用程序。使用启动屏幕绝对不是错误的,它只是通常没那么必要,而且可能会让用户觉得应用优化得不够好。
© 2026 Tauri 贡献者。CC-BY / MIT