gloo
gloo copied to clipboard
utility crate: DOMContentLoaded future
Yosh and I started one at the 2019 Rust All Hands.
Give you a future for when the DOMContentLoaded event has fired.
This is another API which maps very well onto futures-signals: there can be an is_dom_ready() function which returns a Signal<Item = bool> which indicates whether the DOM is ready or not.
As a side note, when implementing this, you need to check document.readyState, because the code might be running after the DOMContentLoaded event has fired.
I published https://github.com/yoshuawuyts/document-ready with the code we had from the all-hands. It still needs to be tested and probably polished a bit more, but happy to move it in here if people think it's useful!
Summary
Add layered APIs for document readiness.
Motivation
Code often doesn't want to start executing until the Web page's DOM has been fully constructed. It might want to grab a handle to a node that might not exist until the DOM is fully loaded. Additionally, one might dynamically add an <iframe> to a Web page and want to wait on the nested <iframe>'s DOM readiness.
Detailed Explanation
Similar to the timers crate, this proposes a layered API where the first layer is the callback-y interface with Rust callbacks instead of wasm_bindgen::Closures or js_sys::Functions, and the second layer is based on Futures on top of the callback-y layer.
-
pub fn is_ready(document: &web_sys::Document) -> bool { ... }Just checks whether
document.readyState !== "loading", which is equivalent to "theDOMContentLoadedevent has already fired". -
pub fn on_ready<F>(document: &web_ses::Document, callback: F) where F: 'static + FnOnce { ... }Checks if the given document is ready, and if so invokes
callbackafter asetTimeout(0). If not, addscallbackas a listener to the documents"DOMContentLoaded"event. -
pub struct DomReady { ... } impl Future for DomReady { type Item = (); type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { ... } } impl DomReady { pub fn top_level() -> Self { ... } pub fn with_document(document: &web_sys::Document) -> Self { ... } }A future that wraps the
on_readyfunction with afutures::oneshotchannel. Has a constructor for the default top-level document and awith_documentconstructor waiting on a particular document's readiness (for example iframe documents).
Drawbacks, Rationale, and Alternatives
We could potentially not take a document argument to simplify the API. However, besides allowing for working with <iframe>s' documents, taking a document argument allows us to more easily test this code and its different cases of ready already vs not ready yet.
We could potentially only expose the future type, and not the is_ready or on_ready functions to simplify the API. However, the implementation of the future type has to have these things under the hood anyways, and in the interest of making low-level, building blocks functionality reusable (maybe someone isn't using futures?) we should expose these functions. It isn't much of a maintenance burden.
We could avoid the setTimeout(0) behavior that ensures that the callback is always invoked on a new tick of the event loop. This gives us slightly better latencies when the document is already ready. However, the motivation for doing it is to cut down on the space of possible behaviors (by making it so that there is no special case of "already loaded" that calls the callback on the same tick of the event loop) and therefore make bugs less likely.
Unresolved Questions
- Should we really do the
setTimeout(0)thing? - Please bike shed the type and function names.
Just checks whether
document.readyState === "complete".
Actually, that corresponds to the "load" event, not the "DOMContentLoaded" event.
So it needs to be document.readyState !== "loading"
Should we really do the
setTimeout(0)thing?
I'm torn on that. There's good arguments for both.
There's also the possibility of using the microtask event loop rather than the macrotask event loop (though that introduces another subtle inconsistency...)
If somebody wants synchronous behavior, they can always manually check is_ready(), so we probably should use setTimeout(0) for consistency.
Please bike shed the type and function names.
I think pub fn on_ready(document: &web_sys::Document) -> impl Future<Output = ()> is actually the best API (with the DomReady type not exposed).
Also, looking at your types, they seem to use Futures 0.1. I think that's a mistake: Futures are nearly stabilized, and so I think we should use Futures 0.3 instead. That also gives us access to async/await, which is huge.
Also, looking at your types, they seem to use Futures 0.1. I think that's a mistake: Futures are nearly stabilized, and so I think we should use Futures 0.3 instead. That also gives us access to async/await, which is huge.
I think we should use 0.1 until 0.3 is published/stable. I'd like to avoid nightly completely. With wasm-bindgen-futures, we intend to switch from 0.1 to 0.3 as soon as it is published/stable, so I think it makes sense to do the same here.
Actually, that corresponds to the
"load"event, not the"DOMContentLoaded"event.So it needs to be
document.readyState !== "loading"
Good catch!
I think
pub fn on_ready(document: &web_sys::Document) -> impl Future<Output = ()>is actually the best API (with theDomReadytype not exposed).
How would you expose the callback-based readiness API?
I think we should use 0.1 until 0.3 is published/stable. I'd like to avoid nightly completely. With wasm-bindgen-futures, we intend to switch from 0.1 to 0.3 as soon as it is published/stable, so I think it makes sense to do the same here.
That's fair, though it wouldn't surprise me if Future becomes stable before Gloo starts to take off, so I'm hesitant to build a lot of things on top of Futures 0.1, simply because of the extra work involved...
How would you expose the callback-based readiness API?
As I proposed in this issue, I would put it into a raw submodule. It would have this type:
pub fn on_ready<F>(document: &Document, f: F) -> Listener<'static, F> where F: FnOnce()
Listener is a struct which is used to implement RAII-based event deregistration. I think we should discuss that in a different issue.
RAII-event deregistration issue posted here: https://github.com/rustwasm/gloo/issues/30