How to tell when the DOM is ready in Dart?

2019-06-27 04:51发布

问题:

I want to get some information about some DOM elements after the page is ready, but I haven't figured out how to tell when this is. I've tried using document.on.contentLoaded and document.on.readyStateChange, but neither seem to work. In the following code, onContentLoaded() and onReadyChanged() never get called.

class WhiteTrace {

  WhiteTrace() {    
  }

  void onContentLoaded(Event e) {
    print("onContentLoaded");
    // This never gets called 
  }

  void onReady() {
    print("onReady");
    // Do stuff
  }

  void onReadyChanged(Event e) {
    print("onReadyStateChanged");
    // This never gets called
    if (document.readyState == "complete") {
      onReady();
      document.on.readyStateChange.remove(onReadyChanged);
    }
  }

  void onResize(Event e) {
    // Do stuff
  }

  void run() {
    write("Hello World!");
    document.on.contentLoaded.add(onContentLoaded);

    window.on.resize.add(onResize);

    document.on.readyStateChange.add(onReadyChanged); 
    print("readyState: " + document.readyState);
    if (document.readyState == "complete") {
      document.on.readyStateChange.remove(onReadyChanged);
      onReady();
    }
  }

  void write(String message) {
    // the HTML library defines a global "document" variable
    document.query('#status').innerHTML = message;
  }
}

void main() {
  new WhiteTrace().run();
}

回答1:

You don't need to care if the DOM is loaded - Darts main does only start when the DOM is fully loaded.

http://www.dartlang.org/articles/embedding-in-html/

"Dart code executes only after the page is parsed. Dart programmers can assume that the DOM is fully loaded."



标签: dom dart