Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Should renderOnDomContentLoaded check document.readyState? #175

Open
sjrd opened this issue Oct 26, 2024 · 1 comment
Open

Should renderOnDomContentLoaded check document.readyState? #175

sjrd opened this issue Oct 26, 2024 · 1 comment

Comments

@sjrd
Copy link

sjrd commented Oct 26, 2024

Hi,

When compiling a Laminar application to Wasm, renderOnDomContentLoaded silently "does nothing". This is because Wasm apps are loaded through a top-level await, which typically means that when the main method executes, the DOM has already loaded.

If a "DOMContentLoaded" listener is registered after the DOM has already loaded, the event never gets fired.

MDN recommends to check as follows:

function doSomething() {
  console.info("DOM loaded");
}

if (document.readyState === "loading") {
  // Loading hasn't finished yet
  document.addEventListener("DOMContentLoaded", doSomething);
} else {
  // `DOMContentLoaded` has already fired
  doSomething();
}

Indeed, I was able to work around the issue by doing the following in my main method in Scala.js:

    if dom.document.readyState == "loading" then
      renderOnDomContentLoaded(dom.document.body, p("hello 1"))
    else
      render(dom.document.body, p("hello 2"))

When compiling to Wasm, "hello 2" shows up.

Should we integrate that test directly into Laminar's renderOnDomContentLoaded so that others don't get confused the way I was? Something like:

   @inline def renderOnDomContentLoaded(
     container: => dom.Element,
     rootNode: => nodes.ReactiveElement.Base
   ): Unit = {
-    documentEvents(_.onDomContentLoaded).foreach { _ =>
-      new RootNode(container, rootNode)
-    }(unsafeWindowOwner)
+    if (dom.document.readyState == "loading") {
+      documentEvents(_.onDomContentLoaded).foreach { _ =>
+        new RootNode(container, rootNode)
+      }(unsafeWindowOwner)
+    } else {
+      new RootNode(container, rootNode)
+    }
   }
@raquo
Copy link
Owner

raquo commented Oct 26, 2024

Oh, good catch, thanks! Lucky that we have this renderOnDomContentLoaded helper method to hide the non-standard condition in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants