Wait until asynchronous operation (firebase) call is done before page loads

微笑、不失礼 提交于 2021-02-08 06:32:13

问题


I'm trying to do perform an asynchronous operation that will grab data and affect the style of my webpage.

Is there a way to make this operation finish before the page loads? Since I want to change an actual attribute of a div element, I know this is unlikely but I'd like to get your guys ideas on how to accomplish this.

Maybe by storing the data in the browser session or something so that it only has to think one? I'm not sure

var grab_user = new Firebase("https://<FIREBASE>.firebaseio.com/users/"+auth.uid);
//grab data from firebase
grab_user.once('value', function (dataSnapshot) {
    var $user = dataSnapshot.val();

    //if the user has this object,
    //change the head color to whats in their settings
    if($user.whitelabel)
        $("#top-header").css('background-color', $user.whitelabel.color);
});

回答1:


Nope. Loading data in Firebase (and pretty much any other part of the modern web) is asynchronous and you'll have to deal with it in your code.

If your div is not properly renderable until the data is available, you should only add it to (or show it on) the page once that data is loaded from Firebase.

So make your header hidden in CSS (#top-header: { display: none }) and then change your code to:

var grab_user = new Firebase("https://<FIREBASE>.firebaseio.com/users/"+auth.uid);
//grab data from firebase
grab_user.once('value', function (dataSnapshot) {
    var $user = dataSnapshot.val();

    //if the user has this object,
    //change the head color to whats in their settings
    if($user.whitelabel) {
        $("#top-header").css('background-color', $user.whitelabel.color);
        $("#top-header").show(); // now we're ready to show the header
    }
});

If the entire page should be hidden until the header has a background color, you can also mark the body as hidden in CSS and then show that when the data is available.



来源:https://stackoverflow.com/questions/27832656/wait-until-asynchronous-operation-firebase-call-is-done-before-page-loads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!