Skip to content

Commit

Permalink
cache string file loading before the first has loaded, #797
Browse files Browse the repository at this point in the history
  • Loading branch information
zepumph committed Sep 23, 2019
1 parent 2291324 commit 0c33bd6
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions js/requirejs-plugins/string.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.<loadedURL:string,Object.<stringKeyName:string, stringValueObject:{value:string}>>}
// Object.<loadedURL:string, StringMap>} - see ChipperStringUtils for typedef of StringMap
// Where stringValueObject is the value of each key in string json files.
const cache = {};

// {Object.<url:string, Array.<function>} - 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 :
Expand All @@ -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' } );
}
Expand Down

0 comments on commit 0c33bd6

Please sign in to comment.