启动画面
在本实验中,我们将在 Tauri 应用中实现基本的启动画面功能。这样做非常简单,启动画面实际上只是在你的应用执行一些繁重的设置相关任务期间创建一个显示一些内容的新窗口,然后在设置完成后关闭它。
¥In this lab we’ll be implementing a basic splashscreen functionality in a Tauri app. Doing so is quite straight forward, a splashscreen is effectively just a matter of creating a new window that displays some contents during the period your app is doing some heavy setup related tasks and then closing it when setting up is done.
先决条件
¥Prerequisites
步骤
¥Steps
-
Before you start developing any project it’s important to build and run the initial template, just to validate your setup is working as intended.
# Make sure you're in the right directorycd splashscreen-lab# Install dependenciespnpm install# Build and run the apppnpm tauri dev -
The easiest way of adding new windows is by adding them directly to
tauri.conf.json
. You can also create them dynamically at startup, but for the sake of simplicity lets just register them instead. Make sure you have a window with the labelmain
that’s being created as a hidden window and a window with the labelsplashscreen
that’s created as being shown directly. You can leave all other options as their defaults, or tweak them based on preference.src-tauri/tauri.conf.json {"windows": [{"label": "main","visible": false},{"label": "splashscreen","url": "/splashscreen"}]} -
Before you begin you’ll need to have some content to show. How you develop new pages depend on your chosen framework, most have the concept of a “router” that handles page navigation which should work just like normal in Tauri, in which case you just create a new splashscreen page. Or as we’re going to be doing here, create a new
splashscreen.html
file to host the contents.What’s important here is that you can navigate to a
/splashscreen
URL and be shown the contents you want for your splashscreen. Try running the app again after this step!/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> -
Since splashscreens are generally intended to be used for the sake of hiding heavy setup related tasks, lets fake giving the app something heavy to do, some in the frontend and some in the backend.
To fake heavy setup in the frontend we’re going to be using a simple
setTimeout
function.The easiest way to fake heavy operations in the backend is by using the Tokio crate, which is the Rust crate that Tauri uses in the backend to provide an asynchronous runtime. While Tauri provides the runtime there are various utilities that Tauri doesn’t re-export from it, so we’ll need to add the crate to our project in order to access them. This is a perfectly normal practice within the Rust ecosystem.
Don’t use
std::thread::sleep
in async functions, they run cooperatively in a concurrent environment not in parallel, meaning that if you sleep the thread instead of the Tokio task you’ll be locking all tasks scheduled to run on that thread from being executed, causing your app to freeze.# Run this command where the `Cargo.toml` file iscd src-tauri# Add the Tokio cratecargo add tokio# 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(())} -
Run the application
You should now see a splashscreen window pop up, both the frontend and backend will perform their respective heavy 3 second setup tasks, after which the splashscreen disappears and the main window is shown!
讨论
¥Discuss
你应该有一个启动画面吗?
¥Should you have a splashscreen?
一般来说,拥有启动画面就意味着承认你无法让你的应用加载速度足够快,因此不需要启动画面。事实上,最好直接转到主窗口,然后在某个角落显示一些小旋转器,通知用户后台仍在进行设置任务。
¥In general having a splashscreen is an admittance of defeat that you couldn’t make your app load fast enough to not need one. In fact it tends to be better to just go straight to a main window that then shows some little spinner somewhere in a corner informing the user there’s still setup tasks happening in the background.
但是,话虽如此,你可能出于风格选择想要使用启动画面,或者你可能有一些非常特殊的要求,导致在执行某些任务之前无法启动应用。拥有启动画面绝对没有错,只是往往没有必要,并且会让用户觉得应用没有得到很好的优化。
¥However, with that said, it can be a stylistic choice that you want to have a splashscreen, or you might have some very particular requirement that makes it impossible to start the app until some tasks are performed. It’s definitely not wrong to have a splashscreen, it just tends to not be necessary and can make users feel like the app isn’t very well optimized.
Tauri 中文网 - 粤ICP备13048890号