formatjs icon indicating copy to clipboard operation
formatjs copied to clipboard

Allow parallel locale & polyfill loading

Open mortargrind opened this issue 1 year ago • 0 comments

Discussed in https://github.com/formatjs/formatjs/discussions/4188

Originally posted by mortargrind September 8, 2023 Hi!

Currently you have to load the polyfill first and then the respective locale data for that polyfill. Which results in unnecessary blocking calls and that results in longer wait times for network conditions where roundtrip time is high.

I believe this can be improved in a non-breaking way. For each locale, what we need to do is add an else block to the current if statement where we check the existence of the polyfill first.

Basically if the polyfill is not present, but if an array under a special name (or a symbol to make it bullet-proof) exists, that the locale data just added to that array.

When the polyfill is loaded later, it can also check this array (again, if only it exists) and iterate over it and call the respective __addLocaleData function.

The idea is prevent this happening: Screenshot 2023-09-08 at 20 31 40

In this screenshot both polyfill and locale data fetching took ~400ms, in total making it ~800ms. We could cut in half basically.

The resulting code would look like this:

In any locale data file:

const localeData = {...}

if (Intl.DateTimeFormat && typeof Intl.DateTimeFormat.__addLocaleData === 'function') {
   Intl.DateTimeFormat.__addLocaleData(localeData)
} else if (globalThis.__FORMAT_JS_DATE_TIME_FORMAT_LOCALES) {
   globalThis.__FORMAT_JS_DATE_TIME_FORMAT_LOCALES.push(localeData)
}

In any polyfill file

 /// rest of the polyfill
if (globalThis.__FORMAT_JS_DATE_TIME_FORMAT_LOCALES) {
   globalThis.__FORMAT_JS_DATE_TIME_FORMAT_LOCALES.forEach((localeData) => {
     Intl.DateTimeFormat.__addLocaleData(localeData)

     // potentially remove the localeData from the array also
   })
}
 
```</div>

mortargrind avatar Jun 03 '24 12:06 mortargrind