頁面加載時,添加進度條,提高用戶體驗

這幾個月做了個項目,在此對一些問題做一個記錄。

項目是前後端分離的,前端用的 npm+webpack。

問題:由於系統某頁面數據量過大或網絡較差等原因,導致頁面還未完全加載出來,但按鈕已被加載時(js還未就緒),點擊按鈕會報錯。

根據系統情況,解決方案:每個頁面加載的時候,在header上方加一個動態的進度條,同時通過css樣式在頁面上覆蓋一個透明的背景,使頁面在加載完成前不可點擊。頁面完全加載後,進度條到100%,然後消失。

方案實施:

1. 在項目的系統公用文件裏建一個loading.js文件,內容如下:

 

module.exports = function() {

    class Process {

        constructor(prop) {

            this.timer = null;

            this.id = `_${(new Date().getTime() + parseInt(Math.random() *1000)).toString(32)}_loading`;

            this.maskId = `_${(new Date().getTime() + parseInt(Math.random() *1000)).toString(32)}_mask`;



            this.loading();

        }

        loading() {

            var html = [

            `<div id="${this.maskId}" class="loading-mask js-loading-mask"></div>`,

            `<div id="${this.id}" class="loading-line-wrap js-loading-line-wrap"><p class="loading-line"></p></div>`

            ], dis = [80, 90], speed = [1, 3], _dis = this.random(dis), _speed =this.random(speed);

            $('body').append(html.join(''));

            this.play(_dis, _speed, 0);

        }

        random(option) {

            var times = option[1] - option[0],

            offset = option[0];

            return Math.random() * times + offset;

        }

        play(dis, speed, num) {

            if(num + speed >= dis) {

                this.timer && clearTimeout(this.timer);

            }else {

                num = num + speed;

            }

            $(`#${this.id}`).css({width: `${num}%`});

            this.timer = setTimeout(()=>{

                this.play(dis, speed, num);
            }, 50);

        }



        completeLoading() {

            this.timer && clearTimeout(this.timer);

            $(`#${this.id}`).stop().animate({width: '100%'}, ()=> {

                $(`#${this.id}`).remove();

                $(`#${this.maskId}`).remove();

            })

        }

    }

    return new Process();

}

 

2. 在系統公用的樣式文件common.scss里加上透明背景及進度條樣式,內容如下:

 

.loading-mask{

    position: fixed;

    top: 0;

    left: 0;

    width: 100%;

    height: 100%;

    background: #000;

    opacity: 0;

    filter:alpha(opacity=0);

}

.loading-line-wrap{

    position: fixed;

    top: 0;

    left: 0;

    width: 0;

    height: 2px;

    background: #2aa7ff;

    z-index: 100000;

}

 

3. 在系統的 main.js文件(系統的入口文件)引入 loading.js並做處理。下面省略了一些不相關的代碼。有//*********的爲此次新增代碼。


 

import loading from './common-component/loading/loading.js';//*********


/**此處省略部分代碼**/



let ajaxObj = {}, ajaxSend = {};//*********

$.ajaxSetup({//*********

    cache: false,//*********

    beforeSend: function(a, b, c, d){//*********

        if(ajaxObj[`_${decodeURIComponent(this.url)}`]) {//*********

            delete ajaxObj[`_${decodeURIComponent(this.url)}`];//*********

        }//*********

        ajaxObj[`_${decodeURIComponent(this.url)}`] = loading();//*********

    }//*********

});//*********



const router = new Router(routes).configure({

    notfound: () => {

        alert('錯誤鏈接!');

    },

    before: () => {

        $("div[id^=easytip-div-main],div.flatpickr-calendar").remove();

        let token = Util.getCookie('token');

        // 每個路徑初始化商品分類

        window.goodsClassify = null;

        ajaxObj = {};//*********

        $('.js-loading-line-wrap,.js-loading-mask').remove();//*********

        $(".classify-dialog").remove();

        if(!token && location.hash.indexOf('/login') < 0){

            window.location.href = '/login.html'

            return false;

        }

        chageText();

        checkCurrentManager(function () {

            detailFun();

        });

    },

    after:() =>{

        sessionStorage.removeItem('funcBtn');

        Object.keys(ajaxSend).map(key=>{//*********

            ajaxSend[key].abort();//*********

        });//*********

        ajaxSend = {};//*********

    }

});

router.init();



//初始化默認路由

if(!Util.getRouter()){

    Util.linkTo('/');

}



// header文字切換

function chageText() {

    let hashCode = window.location.hash,

    $pageTitle = $("#js-page-title"),

    $text = $pageTitle.find('.js-header-title'),

    text = '點擊收起菜單';



    if(hashCode == '#/home-page') {

        text = 'Hi,歡迎登錄xx系統,xxxxxxxx!';

    }else {

        if($('body').hasClass('hide-menu')) {

            text = '點擊展開菜單';

        }

    }

    $text.text(text);

}



function clearLoading(key) {//*********

    if(ajaxObj[`_${decodeURIComponent(st.url)}`]) {//*********

        ajaxObj[`_${decodeURIComponent(st.url)}`].completeLoading();//*********

        delete ajaxObj[`_${st.url}`];//*********

    }//*********

}//*********



/**

* Desc: 用戶未登錄統一攔截模塊.

*/

$(document).ajaxComplete(function(e,xhr,st){

    var status = xhr.status;

    if(ajaxObj[`_${decodeURIComponent(st.url)}`]) {//*********

        ajaxObj[`_${decodeURIComponent(st.url)}`].completeLoading();//*********

        delete ajaxObj[`_${st.url}`];//*********

    }//*********



    if(ajaxSend[`_${decodeURIComponent(st.url)}`]) {//*********

        delete ajaxSend[`_${decodeURIComponent(st.url)}`];//*********

    }//*********

    if(status == 401 ){//用戶未登錄 則刪除token跳轉登錄

        Util.deleteCookie("token",document.domain);

        sessionStorage.clear();

        window.location.href = '/login.html';

    }

}).ajaxSend(function(e,xhr,st){//*********

    ajaxSend[`_${decodeURIComponent(st.url)}`] = xhr;//*********

});



function checkCurrentManager(callback) {//檢查當前操作員密碼狀態

    $.ajax({

        type:'post',

        url:API.checkCurrentManager,

        // async:false,

        success:function(msg){

            if(msg.success){

                callback ? callback() : null;

                let name = ((msg.result || {}).status || {}).name;

                if((msg.result || {}).firstTimeLoginFlag) {//首次登錄,強制修改密碼

                    window.location.href = '/#/modify-pwd?flag=1';

                }else {

                    if(name == 'NORMAL'){//正常

                    }else if(name == 'PASSWORD_INVALIDATE'){//密碼失效

                        $(".passwordTi").addClass('hide');

                        $(".passwordDesc,.passwordStatus").removeClass('hide');

                        Util.linkTo('/modify-pwd');

                    }else if(name == 'NEED_MODIFY_PASSWORD'){//需要修改密碼

                        $(".passwordDesc,.passwordStatus").addClass('hide');

                        $(".passwordTi").removeClass('hide');

                    }

                }

            }else{

                Util.alertMessage(msg.error);

            }

        }

    });

}



function detailFun() {

    let hashCode = window.location.href;

    if(hashCode.indexOf('detail') > -1){

    $("#js-toggle-menu").html('Hi,歡迎登錄xx系統,xxxxxxxx!')

    $("#js-page-title,.js-container-left,.content").css({marginLeft:0});

    $("#js-menu,.header-logo").css({display:'none'});
    
}

}

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章