1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//! Document ready listener for browsers.
//!
//! # Examples
//!
//! ```
//! use wasm_bindgen::prelude::*;
//!
//! #[wasm_bindgen(start)]
//! pub fn main() {
//!     println!("waiting on document to load");
//!     document_ready::ready().await;
//!     println!("document loaded!");
//! }
//! ```

#![forbid(unsafe_code, future_incompatible, rust_2018_idioms)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, missing_doc_code_examples, unreachable_pub)]

use futures_channel::oneshot::channel;
use gloo_events::EventListener;
use std::time::Duration;

/// Wait for the DOM to be loaded.
pub async fn ready() {
    let document = web_sys::window()
        .expect("Window not found")
        .document()
        .unwrap();

    match document.ready_state().as_str() {
        "complete" | "interactive" => {
            futures_timer::Delay::new(Duration::from_secs(0)).await;
        }
        _ => {
            let (sender, receiver) = channel();
            let _listener = EventListener::once(&document, "DOMContentLoaded", move |_| {
                sender.send(()).unwrap();
            });
            receiver.await.unwrap();
        }
    };
}