简体   繁体   中英

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

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);
});

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.

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