等待页面加载之前完成异步操作(firebase)调用
我正在尝试执行异步操作,该操作将获取数据并影响网页的样式.
I'm trying to do perform an asynchronous operation that will grab data and affect the style of my webpage.
有没有办法使此操作在页面加载之前完成?因为我想更改div元素的实际属性,所以我知道这不太可能,但是我想让你们知道如何实现此目的.
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.
也许是通过将数据存储在浏览器会话中或某种方式来使它只需要考虑一个?我不确定
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);
});
不是.在Firebase(以及现代网络的几乎所有其他部分)中加载数据是异步的,因此您必须在代码中进行处理.
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.
如果在数据可用之前,您的 div
无法正确呈现,则只有从Firebase加载数据后,才应将其添加到页面(或在页面上显示).
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.
因此,将标题隐藏在CSS中(#top-header:{display:none}
),然后将代码更改为:
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
}
});
如果应该隐藏整个页面,直到标题具有背景色,您还可以将 body
标记为隐藏在CSS中,然后在数据为可用.
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.