Search code examples
javascripthtml

How to listen for event that next page has started to load?


I'm trying to create a custom "loading" animation that should start when the next page has started loading. In practice, I'd like to receive an event when the browser is starting to load the next toplevel frame regardless if the source of the load event is button click, link activation or JavaScript setting window.location.href. In addition, I'd like to receive the event when the loading is started, not when the next page is ready to be swapped over the current page.

I'd expect the code to be something along the lines

 window.document.addEventListener("???????", function (e) { ... });

can anybody point me to the correct event name?


Solution

  • It seems that window event beforeunload provides correct timing for at least Chrome and Firefox. I haven't yet found any spec that promises this, though.

    The spec says only following (emphasis mine):

    interface BeforeUnloadEvent : Event {
      attribute DOMString returnValue;
    };
    

    Note: There are no BeforeUnloadEvent-specific initialization methods.

    The BeforeUnloadEvent interface is a legacy interface which allows prompting to unload to be controlled not only by canceling the event, but by setting the returnValue attribute to a value besides the empty string. Authors should use the preventDefault() method, or other means of canceling events, instead of using returnValue.

    The returnValue attribute controls the process of prompting to unload. When the event is created, the attribute must be set to the empty string. On getting, it must return the last value it was set to. On setting, the attribute must be set to the new value.

    Note: This attribute is a DOMString only for historical reasons. Any value besides the empty string will be treated as a request to ask the user for confirmation.