aboutsummaryrefslogtreecommitdiffstats
path: root/src/js/utils/load-sprite.js
blob: b4a47f212d96db2cbdcabffe932a5665594a7dbd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// ==========================================================================
// 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) {
          try {
            window.localStorage.setItem(
              `${prefix}-${id}`,
              JSON.stringify({
                content: result,
              }),
            );
          } catch (_) {
            // Do nothing
          }
        }

        update(container, result);
      })
      .catch(() => {});
  }
}