P粉1741519132023-08-16 18:17:53
In markup, there is native syntax (with many variations) that can be used to await promises:
{#await loadLang() then lang} <span>{lang.someValue}</span> {/await}
Another option is to declare a variable in the top scope and set it after the data is loaded. Of course it will be undefined at first, or whatever other value you initialize it to. Then usually combined with {#if}
:
let lang; loadLang().then(l => lang = l);
{#if lang} <span>{lang.someValue}</span> {/if}
Having a guard on browser
is not good. You may want to move the data loading into the layout
loading function so that it can be passed as a data
attribute and can be used during SSR and CSR, and for Available on every page using layout.
Do not use document.documentElement.lang
, instead use the Accept-Language
header of the request on the server.
Loading data before the page is served/rendered also prevents potential layout changes or loading indicators.