{if(browser){ //returnawaitgetLang(document.documentElemen">
I have the following code snippet (layout.svelte):
import { getLang } from "$lib/locale"; import { browser } from "$app/environment"; const loadLang = async () => { if (browser) { // return await getLang(document.documentElement.lang, "home").then( function (data: any) { // const nav = JSON.stringify(data.nav); // console.log(nav) // return nav; // }); const initLocale= await getLang(document.documentElement.lang, "home"); return initLocale.json(); } }; const a = loadLang(); console.log(a);
The purpose of this code is to detect the browser language and the route of the request, and then search for the correct JSON file corresponding to the language and page. But there is a problem, I cannot access the language data of the async loadLang()
in order to use it in the HTML element of the component, except in many answers mentioned here (which is not what I'm looking for) , what I want is a way to access the return value of the above function and use it in an HTML element?
In markup, there isnative syntax (with many variations)that can be used to await promises:
{#await loadLang() then lang} {lang.someValue} {/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}
:{#if lang} {lang.someValue} {/if}
Having a guard on
browser
is not good. You may want to move the data loading into thelayout
loading functionso that it can be passed as adata
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 theAccept-Language
header of the request on the server.Loading data before the page is served/rendered also prevents potential layout changes or loading indicators.