How to show progress bar on web page until web page is fully loaded?

前端 未结 2 1453
轮回少年
轮回少年 2021-02-04 13:55

I would like to show a progress bar/loading popup in a web page until the page is fully loaded.

My web page is heavy because it contains an HTML editor in it, which is a

2条回答
  •  死守一世寂寞
    2021-02-04 14:24

    If a list of resources (javascript files) is available, you can do something like this:

    var loadedResources = 0;
    var deferreds = [];
    var resList = [ 'res1.js', 'res2.js' ];
    
    $.each(resList, function(index, res) {
       var load = $.ajax({
           type: "GET",
           url: res,
           dataType: "script"
       }).then(function() { 
           loadedResources += 1;
    
           //Update progress bar here 
           //Use variable 'loadedResources' and 'resList.length' 
           //to calculate the width of the progess bar
       });
       deferreds.push(load);
    });
    
    $.when.apply(this, deferreds).then(function() {
       //Hide or remove progress bar here because all resources were loaded
    });
    

    Every time when a resource was loaded you update the progress bar. When all resources were loaded you can hide the progress bar.

    $.when.apply() is used to get the deferreds array into one central deferred. If this central deferred is finished, all deferreds 'into' it are finished, too.

    Of course you can also add images etc to the resource list, but then you have to modify the way of loading for the specific resource.

    If needed here you can find more information about Deferred Objects.

    Edit: Obviously you can't see a real process if only one resource is in the resource array.

提交回复
热议问题