diff options
author | Sam Potts <sam@potts.es> | 2020-01-30 14:23:10 +0000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-01-30 14:23:10 +0000 |
commit | 9d512911252cf4835c2b7364cb4ae392cb277a1d (patch) | |
tree | 5e6dcc7647285e49683f05d8a49187e8078d0d2b /src/js/utils/load-sprite.js | |
parent | 44d3a17870949e828e5b1a4619a30dfcb626a174 (diff) | |
parent | b2ac730572ad81aa9755e8b7852c53ceba0e8e9f (diff) | |
download | plyr-9d512911252cf4835c2b7364cb4ae392cb277a1d.tar.lz plyr-9d512911252cf4835c2b7364cb4ae392cb277a1d.tar.xz plyr-9d512911252cf4835c2b7364cb4ae392cb277a1d.zip |
Merge pull request #1663 from sampotts/master
Merge back to beta
Diffstat (limited to 'src/js/utils/load-sprite.js')
-rw-r--r-- | src/js/utils/load-sprite.js | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/src/js/utils/load-sprite.js b/src/js/utils/load-sprite.js new file mode 100644 index 00000000..fe4add00 --- /dev/null +++ b/src/js/utils/load-sprite.js @@ -0,0 +1,75 @@ +// ========================================================================== +// Sprite loader +// ========================================================================== + +import Storage from '../storage'; +import fetch from './fetch'; +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) => { + // eslint-disable-next-line no-param-reassign + 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(() => {}); + } +} |