简体   繁体   中英

How to add preloader to long running function

I develop a custom html page with information about installed certificates on the local machine. The certificate's information I get by crypto provider api, then I filter returned certificates with some restrictions (Issuer, CommonName, etc). This is the work of my function loadCertificates . I show results on button click. But loadCertificates takes some seconds and I want to show preloader before loadCertificates and hide after:

        $("#select__cert-btn").click(function () {
            showPreloader();
            var certificates = loadCertificates(restrictions);
            hidePreloader();
            showCerificates(certificates);
        });

Functions showPreloader and hidePreloader only add/remove div with gif background to the container with certificates info. But when I click on the button my page seems frozen and only after some seconds show results (without appearing my preloader). But in debug mode, before run loadCertificates the preloader is added to html, but it's not visible.

Early I have never the same problem, but it seems like loadCertificates block main thread, but if I'm right why showPreloader not work correclty?

How to solve my problem?

if your loadCertificates function call an endpoint via ajax then you can simply add a html region that will be hide/shown with a gif image (loading) :

<!-- Will be called on every ajax call to show the spinner -->
    <div class="row" id="ajaxLoading" style="display:none">
        <div class="col-md-4 offset-4">
            <img src="~/Images/loading.gif" />
        </div>

    </div>

then add in your scipt file :

var ajaxLoading = $('#ajaxLoading');
//add a spinner to every ajax call
    $(document).ajaxStart(function () {
        ajaxLoading.show();
    });
    $(document).ajaxStop(function () {
        ajaxLoading.hide();
    });

I would try to use a promise so that the loadCertificates runs async without locking the main thread.

Try this:

$("#select__cert-btn").click(function () {
    showPreloader();
    var certificates = new Promise(function(resolve, reject) {
       loadCertificates(restrictions);
       resolve();
    });
    certificates.then(function(result) {
        hidePreloader();
        showCerificates(certificates);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM