我正在尝试执行一个异步操作,该操作将获取数据并影响我的网页样式。
有没有办法在页面加载之前完成此操作?由于我想更改div 元素的实际属性,我知道这不太可能,但我想让你们了解如何实现这一目标。
也许通过将数据存储在浏览器会话或其他东西中,以便它只需要考虑一个?我不确定
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(以及现代网络的任何其他部分)中加载数据是异步的,您必须在代码中处理它。
如果您的div
在数据可用之前无法正确呈现,则只有在从 Firebase 加载数据后,您才应将其添加到网页中(或在页面上显示)。
因此,将标头隐藏在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
}
});
如果整个页面应该隐藏,直到标题具有背景色,您还可以在 CSS 中将body
标记为隐藏,然后在数据可用时显示。