Why is this jQuery unload event being executed immediately after load?

701 Views Asked by At

For some reason, the code in my unload event function below is run immediately when loaded instead of waiting to be unloaded. Why?

Here's a jsfiddle so you can see it in action: http://jsfiddle.net/dillydadally/hsj8xqtx/

HTML:

<input type="button" value="Click me" id="btn"/>

JavaScript:

$('#btn').click(function() {
    var popup = window.open('http://www.stackoverflow.com', 'Window Unload Test', 'width=500,height=500');

    $(popup).unload( function() {
        console.log("here");
    });
});
1

There are 1 best solutions below

1
On

This is happening because when you first create the window it's location is actually about:blank. That then unloads when the URL you specified is requested.

If you change your unload handler to console.log(popup.document.location.href) you'll see its still about:blank.

To mitigate this you might want to wait for the content to load before attaching the unload handler.