mercredi 29 juin 2016

browser waits for web worker to finish before redirecting

I am working on a dashboard web page, it has 5 different square boxes showing the results of heavy queries, usually querying months of data at a time.

Each query could take from 3 to 7 seconds to execute and return data.

What I am trying to achieve from the UI perspective is running those queries in the background and let the UI free to redirect to another page.

My first atempt was a Jquery.ajax() call and the problem there is the following: Let's say that I have 5 queries to run I make the 5 ajax calls and in this example the browser is waiting for query #3 which takes 5 sec the user clicks a and my expectation is for the browser to redirect right away to google, instead it is waiting for task 3 to finish, then ignoring queries 4 and 5 (which is good) and going to google. But since taks 3 takes 5 sec, the user needed to wait 5 extra seconds for a piece of data that he didn't use.

I changed my implementation to web workers and the result is the same.

I am posting a simplified version of the code to express my point. I executed this code in Chrome and the result I am getting is the redirect doesn't happen until the sleep(10) seconds finishes. I want to redirect as soon the user clicks the link.

webWorkerTest.html

<script>
    if(window.Worker){

        var myWorker = new Worker("worker.js");
        var message = { goToTheServer: true };

        myWorker.postMessage(message);

        myWorker.onmessage = function(e){
            console.log(e.data.result);
        };
    }

</script>

<a href="http://www.google.com">Google</a>

worker.js

this.onmessage = function(e){

    if(e.data.goToTheServer != undefined){

        var ajaxResult = goToTheServer(
            function (resultado){
                this.postMessage({result: resultado});
            }           
        );
    }
};


function goToTheServer(callback) {

    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {

               callback(xmlhttp.responseText);                     
           }           
        }
    };

    xmlhttp.open("GET", "ajax.php", true);
    xmlhttp.send(); 
}

ajax.php

<?php

sleep(10); //heavy query
echo 1984;




Aucun commentaire:

Enregistrer un commentaire