简体   繁体   English

等到页面加载之前完成异步操作(firebase)调用

[英]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. 由于我想要更改div元素的实际属性,我知道这不太可能,但我想让你的家伙了解如何实现这一目标。

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. 在Firebase中加载数据(以及现代Web的任何其他部分)都是异步的,您必须在代码中处理它。

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. 如果您的div在数据可用之前无法正确呈现,则只应在从Firebase加载数据后将其添加到页面(或在其上显示)。

So make your header hidden in CSS ( #top-header: { display: none } ) and then change your code to: 因此,将您的标题隐藏在CSS中( #top-header: { display: none } ),然后将您的代码更改为:

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. 如果整个页面应该被隐藏,直到头有一个背景颜色,你还可以标记的body隐藏在CSS,然后表明当数据是可用的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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