ppseprus
ppseprus

Reputation: 548

jQuery .unload() issue in Safari

Im dynamically populating image into a container div, using the $.post() function. Whenever I have a different filtering for the images, I abort the current request, however, I have troubles when navigating to another page on my site. Ive realised, that I should abort the current request there as well, however, it struggles under Safari while not under Chrome.

Initialising the request:

var request = $.post( ... );

When running another one:

request.abort();
request = $.post( ... );

When navigating away, to another page:

$(window).unload(function() { request.abort(); });

Could there be any reason why it does not work or at least, not always under Safari? Thanks!

Upvotes: 1

Views: 9331

Answers (3)

Tamás Pap
Tamás Pap

Reputation: 18283

Please take a look at this question:
Why is jQuery unload not working in chrome and safari?

The unload function is not part of any standard, so you actually can't be sure if the unload function gets called in a browser.

Try:

$(window).on('beforeunload ',function() {
    request.abort();
});

instead.

UPDATE

Another solution can be the following. Your users probably navigate to another page with links. So, using jquery, update the onclick behaviour of links: first abort request, then navigate to the new page.

Upvotes: 2

Bruno Sousa
Bruno Sousa

Reputation: 480

Try this:

window.onbeforeunload = function(e) {
    return 'Safari.';
};

Upvotes: 0

Luigi De Rosa
Luigi De Rosa

Reputation: 720

Unfortunately Safari doesn't support unload event. Instead you should use pagehide.

Here you one example:

<html>
    <head>
    <script>

    function pageShown(evt)
    {
        if (evt.persisted)
            alert("pageshow event handler called.  The page was just restored from the Page Cache.");
        else
            alert("pageshow event handler called for the initial load.  This is the same as the load event.");
    }

    function pageHidden(evt)
    {
        if (evt.persisted)
            alert("pagehide event handler called.  The page was suspended and placed into the Page Cache.");
        else
            alert("pagehide event handler called for page destruction.  This is the same as the unload event.");
    }

    window.addEventListener("pageshow", pageShown, false);
    window.addEventListener("pagehide", pageHidden, false);

    </script>
    <body>
    <a href="http://www.webkit.org/">Click for WebKit</a>
    </body>
    </html>

I suggest you to read this: https://www.webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/

And if it's possibile choose another solution, don't use unload!

Upvotes: 3

Related Questions