啟動畫面
如果您的網頁需要一些時間載入,或是在顯示主視窗前需要在 Rust 中執行初始化程序,啟動畫面可以改善使用者的載入體驗。
設定
首先,在您的 distDir
中建立一個包含 splashscreen HTML 程式碼的 splashscreen.html
。請注意,如果您使用的是基於 Vite 的 Tauri 專案,建議在專案的 public
資料夾中建立 splashscreen.html
,緊鄰 package.json
。
然後,更新您的 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"
+ }
]
現在,您的主視窗將會隱藏,而 splashscreen 視窗會在您的應用程式啟動時顯示。接下來,您需要一個方法來關閉 splashscreen 並在您的應用程式準備好時顯示主視窗。您如何執行此操作取決於您在關閉 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");
}