From 0c33bd65025e372e0fa6877e6118c3b41c47fa81 Mon Sep 17 00:00:00 2001 From: zepumph Date: Mon, 23 Sep 2019 14:33:01 -0800 Subject: [PATCH] cache string file loading before the first has loaded, https://github.com/phetsims/chipper/issues/797 --- js/requirejs-plugins/string.js | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/js/requirejs-plugins/string.js b/js/requirejs-plugins/string.js index 8687def88..e00e6ef41 100644 --- a/js/requirejs-plugins/string.js +++ b/js/requirejs-plugins/string.js @@ -28,10 +28,15 @@ define( require => { // constants // Cache the loaded strings so they only have to be read once through file.read (for performance) - // Object.>} + // Object.} - see ChipperStringUtils for typedef of StringMap // Where stringValueObject is the value of each key in string json files. const cache = {}; + // {Object.} - keep track of actions to trigger once the first load comes back for that + // url. This way there aren't many text.get calls kicked off before the first. + // can come back with text. + const urlsCurrentlyBeingLoaded = {}; + // {string|null} - See documentation of stringTest query parameter in initialize-globals.js const stringTest = ( typeof window !== 'undefined' && window.phet.chipper.queryParameters.stringTest ) ? window.phet.chipper.queryParameters.stringTest : @@ -50,22 +55,28 @@ define( require => { if ( cache[ url ] ) { callback( cache[ url ] ); } + else if ( urlsCurrentlyBeingLoaded[ url ] ) { + + // this url is currently being loaded, so don't kick off another `text.get()`. + urlsCurrentlyBeingLoaded[ url ].push( () => callback( cache[ url ] ) ); + } else { + urlsCurrentlyBeingLoaded[ url ] = []; + // Cache miss: load the file parse, enter into cache and return it text.get( url, loadedText => { - // the cache didn't exist before the text load, but it may exist now. - if ( cache[ url ] ) { - return callback( cache[ url ] ); - } - const parsed = JSON.parse( loadedText ); const isRTL = localeInfo[ phet.chipper.queryParameters.locale ].direction === 'rtl'; - ChipperStringUtils.formatStringValues( parsed, isRTL ); cache[ url ] = parsed; + + // clear the entries added during the async loading process + urlsCurrentlyBeingLoaded[ url ] && urlsCurrentlyBeingLoaded[ url ].forEach( action => action && action() ); + delete urlsCurrentlyBeingLoaded[ url ]; + callback( cache[ url ] ); }, errorBack, { accept: 'application/json' } ); }