crunchy
crunchy

Reputation: 179

Prevent GIF-animation from stopping, when loading other URL

when a link is clicked, a loading animation (GIF) appears and the next url is beeing loaded via window.location.assign().

the GIF-animation stops after a second - although the next site is not loaded yet. How can I make it animate until the next site appears?

I thought about loading the next site into a var and then display it via JS, but I need to have the browser's back-buttons working.

Has someone a idea how to achieve this?

Upvotes: 0

Views: 1021

Answers (1)

Radek Pech
Radek Pech

Reputation: 3098

First need to load the page via AJAX and display it manually:

url = '/api/html?profile=12345';
$.ajax({
    url: url,
    dataType: 'html'
}).always(function(response, status) {
    if ('success' !== status) {
        alert('Error loading page...');
        return;
    }

   //store state for the back and refresh button handler
   if (window.history) {
        history.replaceState({
            reloadUrl: location.href
        }, '', location.href);
        history.pushState({
            reloadHtml: response
        }, '', url);
    } //if(window.history)

    //render new page into current window
    document.open('text/html','replace');
    document.write(response);
    document.close();     
});

To make the back, forward and refresh buttons work, you must add your own handler that will display or reload the page based on saved state:

var allowPopState = false; //fixes popstate in Safari that fires it on every page load
$(function() { setTimeout('allowPopState = true;', 1); }); 

$(window).on('popstate', function(event) {
    if (!history.state) { return; }
    if (!allowPopState && document.readyState === 'complete') {
        event.preventDefault();
        event.stopImmediatePropagation();
        return;
    }

    if (history.state.reloadHtml) {
        document.open('text/html','replace');
        document.write(history.state.reloadHtml);
        document.close();
    } else if (history.state.reloadUrl) {
        if (history.state.reloadUrl === location.href) {
             location.reload();
        } else {
            location.replace(history.state.reloadUrl);
        }
    }
});

This will not completely keep the animation but will minimize the time when browser loads and renders the new page and will allow the animation to continue while the page is being loaded.

To make it even better, you would need to cache all resources for the next page or use lazy-loading on the next page.


Known bug: in desktop Firefox, this will reset page zoom (CTRL + +/- or CTRL + scroll). e.g. When you zoom current the page to 200%, the next page will be displayed in 100% zoom.

Upvotes: 2

Related Questions