diff options
author | Sam Potts <sam@potts.es> | 2018-06-18 21:41:25 +1000 |
---|---|---|
committer | Sam Potts <sam@potts.es> | 2018-06-18 21:41:25 +1000 |
commit | cc3c0b54484e6f5a7b4dba8a36a44f345e462f26 (patch) | |
tree | 5fe2838546d9f981b21572dee88ee7a1c3195477 /src/js/utils/loadSprite.js | |
parent | 4811e3333f1417bc9e14f6cc38afc789e9051c4c (diff) | |
parent | 3c9c1b4cdcd0eb9076c3f0bafbabb057ee140c42 (diff) | |
download | plyr-cc3c0b54484e6f5a7b4dba8a36a44f345e462f26.tar.lz plyr-cc3c0b54484e6f5a7b4dba8a36a44f345e462f26.tar.xz plyr-cc3c0b54484e6f5a7b4dba8a36a44f345e462f26.zip |
Merge branch 'develop'
Diffstat (limited to 'src/js/utils/loadSprite.js')
-rw-r--r-- | src/js/utils/loadSprite.js | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/src/js/utils/loadSprite.js b/src/js/utils/loadSprite.js new file mode 100644 index 00000000..dbb00cf2 --- /dev/null +++ b/src/js/utils/loadSprite.js @@ -0,0 +1,75 @@ +// ========================================================================== +// Sprite loader +// ========================================================================== + +import Storage from './../storage'; +import is from './is'; + +// Load an external SVG sprite +export default function loadSprite(url, id) { + if (!is.string(url)) { + return; + } + + const prefix = 'cache'; + const hasId = is.string(id); + let isCached = false; + + const exists = () => document.getElementById(id) !== null; + + const update = (container, data) => { + container.innerHTML = data; + + // Check again incase of race condition + if (hasId && exists()) { + return; + } + + // Inject the SVG to the body + document.body.insertAdjacentElement('afterbegin', container); + }; + + // Only load once if ID set + if (!hasId || !exists()) { + const useStorage = Storage.supported; + + // Create container + const container = document.createElement('div'); + container.setAttribute('hidden', ''); + + if (hasId) { + container.setAttribute('id', id); + } + + // Check in cache + if (useStorage) { + const cached = window.localStorage.getItem(`${prefix}-${id}`); + isCached = cached !== null; + + if (isCached) { + const data = JSON.parse(cached); + update(container, data.content); + } + } + + // Get the sprite + fetch(url) + .then(result => { + if (is.empty(result)) { + return; + } + + if (useStorage) { + window.localStorage.setItem( + `${prefix}-${id}`, + JSON.stringify({ + content: result, + }), + ); + } + + update(container, result); + }) + .catch(() => {}); + } +} |