graphicore / specimenTools

Apache License 2.0
29 stars 5 forks source link

Keeping track of loaded and loading fonts to avoid duplicate XHRs for same files #28

Closed kontur closed 6 years ago

kontur commented 6 years ago

In my use of the library one recurring performance problem is the XHR based font loading, which does not cache the request and so might re-load a font file several times on a page. E.g. a family page that has each style as a tester you can type with, but also all other styles available via a dropdown would load each style for as many times as there is styles, so instead of say 8 x 30kb it might be 64 x 30kb!

This PR logs what files have been loaded or are being loaded and circumvents duplicate XHR requests, so each unique file path is at most loaded only once.

If several instances load the same file on startup, the "queue"ing comes into effect. If fonts are loaded after the initial setup (not a common scenario with one initial setup, but possible), the "loaded" checks come into effect.

You can test this by changing the fonts being loaded in the multiple example to have the same file in several of the font lists. Using the multiple example's main.js loadFonts.fromUrl(pubsub, fontFilesForInstance); call in main() inside a timeout for a second time demos the reaction to already loaded files.

graphicore commented 6 years ago

Thanks for suggesting this. I agree with the need and usefulness of a cache here. But, I'm sorry I'm not going to merge this as it is. loaded and queue are side effects on the module level. I.e. the module itself changes it's behavior. This is a bad thing to do and I generally avoid it. I'll look into this later today, maybe we can just inject loaded and queue as arguments into the functions, so the state can be controlled from the caller or we make a class out of the module, so that its instances contain the side effects.

kontur commented 6 years ago

Roger, I see your reasoning. Any other way to go about this is more than welcome, and where I can, I'm happy to help.