tiptap/examples/helpers/svg-sprite-loader.js

74 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-07-09 00:39:42 +08:00
'use strict';
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
var isSvg = document.createElementNS && document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' ).createSVGRect;
var localStorage = 'localStorage' in window && window['localStorage'] !== null ? window.localStorage : false;
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
function svgSpriteInjector(source, opts) {
var file;
opts = opts || {};
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
if (source instanceof Node) {
file = source.getAttribute('data-svg-sprite');
opts.revision = source.getAttribute('data-svg-sprite-revision') || opts.revision;
} else if (typeof source === 'string') {
file = source;
}
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
if (isSvg) {
if (file) {
injector(file, opts);
2018-11-09 05:03:10 +08:00
} else {
2020-07-09 00:39:42 +08:00
console.error('svg-sprite-injector: undefined sprite filename!');
2018-11-09 05:03:10 +08:00
}
2020-07-09 00:39:42 +08:00
} else {
console.error('svg-sprite-injector require ie9 or greater!');
}
};
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
function injector(filepath, opts) {
var name = 'injectedSVGSprite' + filepath,
revision = opts.revision,
request;
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
// localStorage cache
if (revision !== undefined && localStorage && localStorage[name + 'Rev'] == revision) {
return injectOnLoad(localStorage[name]);
2018-11-09 05:03:10 +08:00
}
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
// Async load
request = new XMLHttpRequest();
request.open('GET', filepath, true);
request.onreadystatechange = function (e) {
var data;
if (request.readyState === 4 && request.status >= 200 && request.status < 400) {
injectOnLoad(data = request.responseText);
if (revision !== undefined && localStorage) {
localStorage[name] = data;
localStorage[name + 'Rev'] = revision;
2018-11-09 05:03:10 +08:00
}
}
2020-07-09 00:39:42 +08:00
};
request.send();
}
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
function injectOnLoad(data) {
if (data) {
if (document.body) {
injectData(data);
} else {
document.addEventListener('DOMContentLoaded', injectData.bind(null, data));
2018-11-09 05:03:10 +08:00
}
}
2020-07-09 00:39:42 +08:00
}
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
function injectData(data) {
var body = document.body;
body.insertAdjacentHTML('afterbegin', data);
if (body.firstChild.tagName === 'svg') {
body.firstChild.style.display = 'none';
2018-11-09 05:03:10 +08:00
}
2020-07-09 00:39:42 +08:00
}
2018-08-21 05:02:21 +08:00
2020-07-09 00:39:42 +08:00
export default svgSpriteInjector;