document_ready/
lib.rs

1//! Document ready listener for browsers.
2//!
3//! # Examples
4//!
5//! ```
6//! use wasm_bindgen::prelude::*;
7//!
8//! #[wasm_bindgen(start)]
9//! pub fn main() {
10//!     println!("waiting on document to load");
11//!     document_ready::ready().await;
12//!     println!("document loaded!");
13//! }
14//! ```
15
16#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
17#![deny(missing_debug_implementations, nonstandard_style)]
18#![warn(missing_docs, missing_doc_code_examples, unreachable_pub)]
19
20use futures_channel::oneshot::channel;
21use gloo_events::EventListener;
22use std::time::Duration;
23
24/// Wait for the DOM to be loaded.
25pub async fn ready() {
26    let document = web_sys::window()
27        .expect("Window not found")
28        .document()
29        .unwrap();
30
31    match document.ready_state().as_str() {
32        "complete" | "interactive" => {
33            futures_timer::Delay::new(Duration::from_secs(0)).await;
34        }
35        _ => {
36            let (sender, receiver) = channel();
37            let _listener = EventListener::once(&document, "DOMContentLoaded", move |_| {
38                sender.send(()).unwrap();
39            });
40            receiver.await.unwrap();
41        }
42    };
43}