aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/utils/load-sprite.js
diff options
context:
space:
mode:
authorSam Potts <sam@potts.es>2019-06-21 00:19:37 +1000
committerSam Potts <sam@potts.es>2019-06-21 00:19:37 +1000
commit8fc6c2ba526bf1ef8cdb9476f1644089281ce60d (patch)
tree059c236189936bde02572ce70be6a96390b4a585 /src/js/utils/load-sprite.js
parentc4b3e0672e86f2a2786f315bf8f54250cd1f7f78 (diff)
downloadplyr-8fc6c2ba526bf1ef8cdb9476f1644089281ce60d.tar.lz
plyr-8fc6c2ba526bf1ef8cdb9476f1644089281ce60d.tar.xz
plyr-8fc6c2ba526bf1ef8cdb9476f1644089281ce60d.zip
File rename and clean up
Diffstat (limited to 'src/js/utils/load-sprite.js')
-rw-r--r--src/js/utils/load-sprite.js75
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(() => {});
+ }
+}